利用 js 實現彈出蒙板(model)功能

關於 js 實現一個簡單的蒙板功能(model)

思路:

  • 建立一個蒙板, 設置蒙板的堆疊順序保證能將其它元素蓋住
position: absolute;
top: 0;
left: 0;
display: none;
background-color: rgba(9, 9, 9, 0.63);
width: 100%;
height: 100%;
z-index: 1000;
  • 設置蒙板中內容的背景色和展現格式
width: 50%;
text-align: center;
background: #ffffff;
border-radius: 6px;
margin: 100px auto;
line-height: 30px;
z-index: 10001;
  • 綁定事件, 動態切換蒙板的 display 屬性
function showModel() {
    document.getElementById('myModel').style.display = 'block';
}
function closeModel() {
    document.getElementById('myModel').style.display = 'none';
}

注意事項: 蒙板要採用絕對定位, 寬和高要佔満整個頁面, 堆疊順序要大html

源代碼

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>蒙板</title>
    <style>
        .container {
            width: 900px;
            margin: 50px auto;
            text-align: center;
        }

        #myModel {
            position: absolute;
            top: 0;
            left: 0;
            display: none;
            background-color: rgba(9, 9, 9, 0.63);
            width: 100%;
            height: 100%;
            z-index: 1000;
        }

        .model-content {
            width: 50%;
            text-align: center;
            background: #ffffff;
            border-radius: 6px;
            margin: 100px auto;
            line-height: 30px;
            z-index: 10001;
        }
    </style>
</head>
<body>
<div class="container">
    <button onclick="showModel()">彈出蒙板</button>
    <div id="myModel" onclick="closeModel()">
        <div class="model-content">
            <p>你好啊,我是內容~~</p>
            <p>
                <button id="closeModel" onclick="closeModel()">關閉</button>
            </p>
        </div>
    </div>
</div>
<script>
    function showModel() {
        document.getElementById('myModel').style.display = 'block';
    }
    function closeModel() {
        document.getElementById('myModel').style.display = 'none';
    }
</script>
</body>
</html>
相關文章
相關標籤/搜索