最近的一個專案,設計稿上有個地方是彈出層,但是沒有看見關閉按鈕或者關閉圖片,這讓我很疑惑,這要怎麼關閉?使用者體驗不會變差麼?但想了想無所謂了,大不了以後再改,加個按鈕或者圖片點選隱藏而已,於是我就按著設計稿上的做了,今天特地分享出來(預設樣式因為是單獨一個css檔案,太長,就用 * 強制清除預設樣式了,但是推薦不這樣用,至於為什麼可以百度)。
接下來貼程式碼,首先是css的:
* {
margin: 0;
padding: 0;
}
html,body {
width: 100%;
height: 100%;
}
.containenr {
width: 100%;
height: 100%;
overflow-y: auto;
overflow-x: hidden;
background: url(./images/xiaolv.jpg)no-repeat;
background-size: cover;
position: relative;
}
.dialog {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
background: rgba(0, 0, 0, .7);
}
.content {
width: 600px;
height: 600px;
background-color: yellow;
position: absolute;
top: 50%;
left: 50%;
margin-top: -300px;
margin-left: -300px;
}
.btn {
width: 200px;
height: 40px;
text-align: center;
line-height: 40px;
color: red;
font-weight: 600;
background-color: aquamarine;
margin: 0 auto;
cursor: pointer;
}
.hide {
display: none;
}
然後是頁面的佈局,比較簡單:
<div class="containenr">
<div id="btn" class="btn">點我顯示遮罩層</div>
<div id="dialog" class="dialog hide">
<div id="content" class="content"></div>
</div>
</div>
最後是js,也比較簡單:
window.onload = function () {
var dialog = document.getElementById('dialog');
var content = document.getElementById('content');
var btn = document.getElementById('btn');
//點選顯示遮罩層
btn.onclick = function () {
dialog.classList.remove('hide');
// dialog.style.display = 'block';
}
//點選除黃色區域隱藏遮罩層
dialog.addEventListener('click',function(e){
//阻止冒泡
window.event ? window.event.cancelBubble = true : e.stopPropagation();
var e = window.e || e;
var el = e.target || e.srcElement;
//獲取當前點選區域的className
var el_name = el.className;
console.log(el_name);
//如果點選區域等於內容區域就return,否則就隱藏
if(el_name == 'content') {
return;
}else {
dialog.classList.add('hide');
// dialog.style.display = 'none';
}
})
}
到此為止這次分享就結束了,本人也是自學的前端現在在實習,技術有限可能會有不足的地方希望大神能指點,有問題可以回覆討論,最後希望能看到本篇文章的前端小夥伴早日成為巨佬,共勉!
本文章已修改原文用詞符合繁體字使用者習慣使其容易閱讀
版權宣告:此處為CSDN博主「於離別之朝束起約定之花」的原創文章,依據CC 4.0 BY-SA版權協議,轉載請附上原文出處連結及本宣告。
原文連結:https://blog.csdn.net/qq_43398736/article/details/101298220