jquery寫一個(gè)彈出框及遮罩層效果

HTML:

 <!DOCTYPE html>
 <html lang="en">
 <head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Document</title>
 </head>
 <body>
   <input type="submit" value="點(diǎn)我">
   <!-- 提交按鈕彈出DOM部分 -->
   <div class="mask"></div>
   <div class="box">
    <!-- 關(guān)閉按鈕 -->
    <a class="open">X</a>
    <!-- 內(nèi)容 -->
    哈哈哈哈哈哈哈
   </div>
 </body>
 </html>

javascript:

<script src="jquery.js"></script>
<script>
 $(document).ready(function(){
  $("input").click(function(e){
    // 阻止默認(rèn)提交表單事件
    e.preventDefault();
    // 將彈框位置居中
    center($(".box"));
    // 遮罩層顯示,此處window也可以換成document,區(qū)別在于遮罩層高度的差別
    $('.mask').show().height($(window).height());
    // 彈框顯示
    $('.box').show();
    //彈框彈出后隱藏掉滑動(dòng)條,阻止了滾輪對(duì)頁(yè)面的控制
    $("body").css({overflow:"hidden"});
    
  });
}).keydown(function(e){         //document監(jiān)聽按下esc將關(guān)閉彈出框及遮罩層
  if(e.keyCode==27){
    $('.mask').hide();
    $('.box').hide();
    // 重新顯示滑動(dòng)條
    $("body").css({overflow:"auto"});
  }
})
// 關(guān)閉按鈕
$('.open').click(function(e) {
  func_close();
})
// 關(guān)閉函數(shù)
function func_close(){
      $('.mask').hide();
      $('.box').hide();
      // 重新顯示滑動(dòng)條
      $("body").css({overflow:"auto"});
    }
// 居中函數(shù)
function center(obj){
  var screenWidth = $(window).width(), screenHeight = $(window).height(); //當(dāng)前瀏覽器窗口的 寬高
  var scrolltop = $(window).scrollTop();//獲取當(dāng)前窗口距離頁(yè)面頂部高度
  var objLeft = (screenWidth - obj.width())/2;
  var objTop = (screenHeight - obj.height())/2 + scrolltop;
  obj.css({"left": objLeft + 'px', "top": objTop + 'px','display': 'block'});
}
</script>

CSS:

 /*遮罩層樣式*/
.mask{
  display:none;
  position:absolute;
  z-index:10;
  left:0;
  top:0;
  width:100%;
  height:100%;
  background:#666;
  opacity:0.5;
  -moz-opacity:0.5;
  filter:alpha(opacity=50)
}
/*彈出框樣式*/
.box{
  z-index:999;
  display:none;
  position: relative;
  width:340px;
  height:180px;
  border:solid 1px #999;
  border-radius:5px;
  background-color:#fff;
  box-shadow:0 0 0 1px #00aff0;
  text-align:center;
  padding-top: 20px;
}
/* 關(guān)閉按鈕 */
.open {
  position: absolute;
  top: 0;
  right: 10px;
}
/*按鈕樣式*/
input{
  display:block;
  width:100px;
  height:30px;
  outline:none;
  cursor:pointer;
  font-size:16px;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容