JavaScript-js 如何实现弹出层拖动效果

JavaScript-js 如何实现弹出层拖动效果

归属感 发布于 2017-06-11 字数 296 浏览 957 回复 3

可能重复的问题
求纯javascript实现一个拖拽效果的程序

我页面里有个div标签,

<div id="msgLayer" style="display:none"></div>

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

虐人心 2017-10-21 3 楼

分享给你一段代码吧,方式为rDrag.init(obj),obj是div对象。

 var rDrag = {
o:null,
init:function(o){
o.onmousedown = this.start;
},
start:function(e){
var o;
e = rDrag.fixEvent(e);
e.preventDefault && e.preventDefault();
rDrag.o = o = this;
o.x = e.clientX - rDrag.o.offsetLeft;
o.y = e.clientY - rDrag.o.offsetTop;
document.onmousemove = rDrag.move;
document.onmouseup = rDrag.end;
},
move:function(e){
e = rDrag.fixEvent(e);
var oLeft,oTop;
oLeft = e.clientX - rDrag.o.x;
oTop = e.clientY - rDrag.o.y;
rDrag.o.style.left = oLeft + 'px';
rDrag.o.style.top = oTop + 'px';
},
end:function(e){
e = rDrag.fixEvent(e);
rDrag.o = document.onmousemove = document.onmouseup = null;
},
fixEvent: function(e){
if (!e) {
e = window.event;
e.target = e.srcElement;
e.layerX = e.offsetX;
e.layerY = e.offsetY;
}
return e;
}
}

甜柠檬 2017-06-27 1 楼

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>代码非常简洁且兼容多浏览器的拖动层</title>
</head>
<body>
<div id="f" style="position: absolute; width: 500px; height: 350px; background-color: #ccc; top: 150px; left: 200px; z-index: 101; border: solid 1px blue;">
<div id="title" style="background-color: Blue; cursor: move; height: 20px; color: #fff;font-size: 13px; padding-top: 5px; padding-left: 10px;">这里是层标题</div>
</div>
<script type="text/javascript">
var posX;
var posY;
fdiv = document.getElementById("f");
document.getElementById("title").onmousedown=function(e)
{
if(!e) e = window.event;
posX = e.clientX - parseInt(fdiv.style.left);
posY = e.clientY - parseInt(fdiv.style.top);
document.onmousemove = mousemove;
}
document.onmouseup = function()
{
document.onmousemove = null;
}
function mousemove(ev)
{
if(ev==null) ev = window.event;
fdiv.style.left = (ev.clientX - posX) + "px";
fdiv.style.top = ev.clientY - posY + "px";
}
</script>
</body>
</html>