纯原生js自定义弹窗

1.HTML






2.css

/* 弹窗 (background) */
.modal {
    display: none; /* 默认隐藏 */
    position: fixed; 
    z-index: 1; 
    left: 0;
    top: 0;
    width: 100%; 
    height: 100%; 
    overflow: auto; 
    background-color: rgba(0,0,0,0.4);
}

/* 弹窗内容 */
.modal-content {
    position: relative;
    background-color: #fefefe;
    cursor: pointer;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    padding: 0;
    border: 1px solid #888;
    width: 50%;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
    -webkit-animation-name: animatetop;
    -webkit-animation-duration: 0.4s;
    animation-name: animatetop;
    animation-duration: 0.4s
}

/* 添加动画 */
@-webkit-keyframes animatetop {
    from {top:-300px; opacity:0} 
    to {top:50%; opacity:1}
}

@keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:50%; opacity:1}
}

/* 关闭按钮 */
.close {
    color: white;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}

.modal-header {
    padding: 2px 16px;
    background-color: #5cb85c;
    color: white;
}

.modal-body {padding: 2px 16px;}

.modal-footer {
    padding: 2px 16px;
    background-color: #5cb85c;
    color: white;
}

3.js

// 获取弹窗
var modal = document.getElementById('myModal');

// 打开弹窗的按钮对象
var btn = document.getElementById("myBtn");

// 获取  元素,用于关闭弹窗 that closes the modal
var span = document.getElementsByClassName("close")[0];

// 点击按钮打开弹窗
btn.onclick = function() {
    modal.style.display = "block";
}

// 点击  (x), 关闭弹窗
span.onclick = function() {
    modal.style.display = "none";
}

// 在用户点击其他地方时,关闭弹窗
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

你可能感兴趣的:(javascript,css,前端)