JS拖动–setCapture
最近,在给图片墙的我是微博控部分加滚动条~所以做到拖动图片的部分了~实话是不想用插件,然后自己写了一两个又觉得自己写的好笨,于是百度了拖拽的思路,看自己的思路是否对~果然,找到比较简介的。也遇到比较篇的函数和方法~记录并学习之。
鼠标捕获(setCapture)作用是将鼠标事件捕获到当前文档的指定的对象。这个对象会为当前应用程序或整个系统接收所有鼠标事件
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<style type="text/css">
#drag{position:absolute;left:12px;top:24px;width:100px;height:150px; display:block;border:1px solid #000000;z-index:1;background:#eeeeee; cursor: pointer;}
</style>
</head>
<body>
<div id="drag"></div>
<script type="text/javascript">
<!--
window.onload=function(){
objDiv = document.getElementById('drag');
drag(objDiv);
};function drag(dv){
dv.onmousedown=function(e){
var d=document;
e = e || window.event;
var x= e.layerX || e.offsetX;
var y= e.layerY || e.offsetY;
//设置捕获范围
if(dv.setCapture){
dv.setCapture();
}else if(window.captureEvents){
window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);
}
d.onmousemove=function(e){
e= e || window.event;
if(!e.pageX)e.pageX=e.clientX;
if(!e.pageY)e.pageY=e.clientY;
document.getElementById("drag").innerHTML= e.pageX+ e.pageY;
var tx=e.pageX-x;
var ty=e.pageY-y;
dv.style.left=tx+"px";
dv.style.top=ty+"px";
};
d.onmouseup=function(){
//取消捕获范围
if(dv.releaseCapture){
dv.releaseCapture();
}else if(window.captureEvents){
window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
}
//清除事件
d.onmousemove=null;
d.onmouseup=null;
};
};
}
//-->
</script>
</body>
</html>
也就是当触发元素设置了相对或者绝对定位后,几乎相等,唯一不同就是一个从border为参考点,一个以内容为参考点。
$(function(){
var dragging = false;
var iX, iY;
$("#drag").mousedown(function(e) {
dragging = true;
iX = e.clientX - this.offsetLeft;
iY = e.clientY - this.offsetTop;
this.setCapture && this.setCapture();
return false;
});
document.onmousemove = function(e) {
if (dragging) {
var e = e || window.event;
var oX = e.clientX - iX;
var oY = e.clientY - iY;
$("#drag").css({"left":oX + "px", "top":oY + "px"});
return false;
}
};
$(document).mouseup(function(e) {
dragging = false;
$("#drag")[0].releaseCapture();
e.cancelBubble = true;
})})
</script>