用js实现拖拽功能
平常我们在网上可以看到,按住一张图片,然后拖到另一处去,前天在网上看石川(Blue)老师 的js课堂,有见过这个,写下来与大家分享一下:
1,先画个div小红块,样式设置如下:
#div1{width: 200px; height: 200px; background-color: red; position:absolute;}
这里的positon属性很重要,如果没有这个,根本拖不动你可以试一下。
2,然后需要用到三个事件,onmousedown, onmousemove, onmouseup
onmousedown,鼠标按下时,需要取得鼠标的坐标:
disX = evnt.clientX - oTxt.offsetLeft; disY = evnt.clientY - oTxt.offsetTop;
鼠标坐标-红块左上角坐标,取得距离;
2,onmousemove,当鼠标移动时,鼠标坐标变化,红块进行重画,重画的坐标与原来保持一致:
var x = evnt.clientX - disX; var y = evnt.clientY - disY; oTxt.style.left = x + "px"; oTxt.style.top = y + "px";
3,onmouseup,当鼠标放开时,红块停止,这时候需要做的时把前两个事件为空:
document.onmousemove = null; document.onmouseup = null;
4,当然以上还远远不够,当你拖动的过快时候,红块会脱离窗口,你可以尝试删除试一下,代码如下:
if( x<0 ){ x = 0; } else if (x>document.documentElement.clientWidth-oTxt.offsetWidth){ x = document.documentElement.clientWidth-oTxt.offsetWidth; } if (y > document.documentElement.clientHeight-oTxt.offsetHeight){ y = document.documentElement.clientHeight-oTxt.offsetHeight; }else if( y<0 ) { y = 0; }
自己理解吧:
全部代码如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>拖拽</title> <style type="text/css"> #div1{width: 200px; height: 200px; background-color: red; position:absolute;} </style> <script type="text/javascript" charset="utf-8"> window.onload = function() { var disX = 0; var disY = 0; var oTxt = document.getElementById("div1"); oTxt.onmousedown = function (ev) { var evnt = ev || event; disX = evnt.clientX - oTxt.offsetLeft; disY = evnt.clientY - oTxt.offsetTop; document.onmousemove = function(ev) { var evnt = ev || event; var x = evnt.clientX - disX; var y = evnt.clientY - disY; if( x<0 ){ x = 0; } else if (x>document.documentElement.clientWidth-oTxt.offsetWidth){ x = document.documentElement.clientWidth-oTxt.offsetWidth; } if (y > document.documentElement.clientHeight-oTxt.offsetHeight){ y = document.documentElement.clientHeight-oTxt.offsetHeight; }else if( y<0 ) { y = 0; } oTxt.style.left = x + "px"; oTxt.style.top = y + "px"; } document.onmouseup = function() { document.onmousemove = null; document.onmouseup = null; } return false; } } </script> </head> <body> <div id="div1"> </div> </body> </html>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。