可以限定拖動範圍的彈出視窗效果程式碼例項

antzone發表於2017-04-01

本章節分享一段非常實用的程式碼例項,它實現了點選彈出居中視窗效果,並且可以實現點選關閉視窗。

最為實用的一點,就是彈出視窗可以隨意拖動,且被限制在文件區域。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
html, body{
  height:100%;
  overflow:hidden;
}
body, div, h2{
  margin:0;
  padding:0;
}
body{font: 12px/1.5 Tahoma;}
center{padding-top: 10px;}
button{cursor: pointer;}
#win{
  position: absolute;
  top:50%;
  left:50%;
  width:400px;
  height:200px;
  background:#fff;
  border:4px solid #f90;
  margin:-102px 0 0 -202px;
  display:none;
}
h2{
  font-size:12px;
  height:18px;
  text-align:right;
  background:#FC0;
  border-bottom:3px solid #f90;
  padding:5px;
  cursor:move;
}
h2 span{
  color:#f90;
  cursor:pointer;
  background:#fff;
  border:1px solid #f90;
  padding:0 2px;
}
</style>
<script>
window.onload = function (){
  var oWin=document.getElementById("win");
  var oBtn=document.getElementsByTagName("button")[0];
  var oClose=document.getElementById("close");
  var oH2=oWin.getElementsByTagName("h2")[0];
  var bDrag=false;
  var disX=disY=0;
  oBtn.onclick=function(){
    oWin.style.display="block" 
  };
  oClose.onclick=function(){
    oWin.style.display="none";
  };
  oClose.onmousedown=function (event){
    (event || window.event).cancelBubble=true;
  };
  oH2.onmousedown=function (event){  
    var event=event || window.event;
    bDrag = true;
    disX = event.clientX - oWin.offsetLeft;
    disY = event.clientY - oWin.offsetTop;  
    this.setCapture && this.setCapture();  
    return false
  };
  document.onmousemove = function (event){
    if (!bDrag) return;
    var event = event || window.event;
    var iL = event.clientX - disX;
    var iT = event.clientY - disY;
    var maxL = document.documentElement.clientWidth - oWin.offsetWidth;
    var maxT = document.documentElement.clientHeight - oWin.offsetHeight;  
    iL = iL < 0 ? 0 : iL;
    iL = iL > maxL ? maxL : iL;   
    iT = iT < 0 ? 0 : iT;
    iT = iT > maxT ? maxT : iT;
   
    oWin.style.marginTop = oWin.style.marginLeft = 0;
    oWin.style.left = iL + "px";
    oWin.style.top = iT + "px";  
    return false
  };
  document.onmouseup=window.onblur=oH2.onlosecapture=function (){
    bDrag = false;    
    oH2.releaseCapture && oH2.releaseCapture();
  };
};
</script>
</head>
<body>
<div id="win">
  <h2><span id="close">×</span></h2>
</div>
<center><button>點選彈出層</button></center>
</body>
</html>

相關文章