本文为大家分享了原生弹窗拖拽代码demo,供大家参考,具体内容如下
效果图:
实现代码:
弹窗拖拽*{margin:0;padding:0;}
.box{position: absolute;width: 400px;height: 300px;top:100px;left:100px;border:1px solid #001c67;background: #}
.move{position: absolute;width: 100px;height: 100px;top:100px;left:150px;border:1px solid #000;}
.move:hover{cursor: move;}
.close{position: absolute;width: 30px;height: 30px;top:0px;right:0px;background:red;text-align: center;line-height: 30px;}
window.οnlοad=function(){
var oMove=document.getElementById('move');
// 拖曳
oMove.οnmοusedοwn=fnDown;
// 关闭
var oClose=document.getElementById('close');
oClose.οnclick=function(){
document.getElementById('box').style.display='none';
}
}
function fnDown(event){
event = event || window.event;
var oDrag=document.getElementById('box'),
// 光标按下时光标和面板之间的距离
disX=event.clientX-oDrag.offsetLeft,
disY=event.clientY-oDrag.offsetTop;
// 移动
document.οnmοusemοve=function(event){
event = event || window.event;
var l=event.clientX-disX,
t=event.clientY-disY,
// 最大left,top值
leftMax=(document.documentElement.clientWidth || document.body.clientWidth)-oDrag.offsetWidth,
topMax=(document.documentElement.clientHeight || document.body.clientHeight)-oDrag.offsetHeight;
if(l<0) l=0;
if(l>leftMax) l=leftMax;
if(t<0) t=0;
if(t>topMax) t=topMax;
oDrag.style.left=l+'px';
oDrag.style.top=t+'px';
}
// 释放鼠标
document.οnmοuseup=function(){
document.οnmοusemοve=null;
document.οnmοuseup=null;
}
}
主要注意几点:
1.event,IE兼容问题
2.点击鼠标时要先判断鼠标与面板之间的距离
3.要判断弹窗与浏览器整个区域的距离,不能让弹窗跑出浏览器外的区域
4.松开鼠标要解除事件绑定,不然会有bug
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。