用js實(shí)現(xiàn)彈出圖層
用js實(shí)現(xiàn)一個(gè)彈出圖層,具體效果:
點(diǎn)擊按鈕后彈出圖層,圖層處于頁(yè)面中間、帶有陰影的圓角邊框、圖層中有input、提交按鈕、關(guān)閉按鈕、標(biāo)題,彈出后背景頁(yè)面不可點(diǎn)擊、背景變灰。所有代碼不分開(kāi)、放在一個(gè)html中顯示。
?
以下是一個(gè)簡(jiǎn)單的JavaScript代碼示例:
<!DOCTYPE html>
<html>
<head>
<title>彈出圖層</title>
<style>
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 9999;
display: none;
}
.popup {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
text-align: center;
}
h2 {
margin-top: 0;
}
input[type="text"] {
padding: 10px;
margin: 10px 0;
border-radius: 5px;
border: none;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
width: 100%;
box-sizing: border-box;
}
button {
padding: 10px 20px;
background-color: #1c7cd6;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #15549a;
}
.close {
position: absolute;
top: 10px;
right: 10px;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: #ccc;
color: #fff;
font-size: 14px;
text-align: center;
line-height: 20px;
cursor: pointer;
}
.close:hover {
background-color: #999;
}
</style>
</head>
<body>
<button id="open-popup">打開(kāi)彈出圖層</button>
<div id="overlay">
<div>
<h2>彈出圖層</h2>
<input type="text" placeholder="請(qǐng)輸入內(nèi)容">
<button>提交</button>
<div id="close-popup">×</div>
</div>
</div>
<script>
var openPopupButton = document.getElementById("open-popup");
var closePopupButton = document.getElementById("close-popup");
var overlay = document.getElementById("overlay");
?
openPopupButton.onclick = function() {
overlay.style.display = "block";
document.body.style.overflow = "hidden";
}
?
closePopupButton.onclick = function() {
overlay.style.display = "none";
document.body.style.overflow = "auto";
}
</script>
</body>
</html>
?
該代碼使用了CSS樣式,包含一個(gè)按鈕和一個(gè)彈出圖層。單擊按鈕將調(diào)用JavaScript函數(shù)來(lái)顯示圖層,并將背景頁(yè)面設(shè)為不可點(diǎn)擊狀態(tài)。關(guān)閉按鈕也是通過(guò)JavaScript函數(shù)來(lái)實(shí)現(xiàn)的,當(dāng)用戶單擊關(guān)閉按鈕時(shí),它將隱藏彈出框并將背景頁(yè)面狀態(tài)還原。如果想隱藏JS功能邏輯,可用JShaman對(duì)JS代碼進(jìn)行混淆加密,加密后的代碼是密文狀態(tài),不可讀、不可分析。