JavaScript 拖拽效果实现
我们在访问一些网站时,会发现有些内容是可以拖拽的,比较方便,那么使用JS怎么实现呢?今天结合代码展示下拖拽效果的实现。
这里需要先熟悉下几个JS事件:
onmousedown:鼠标点击按下时触发
onmousemove:鼠标移动时触发
onmouseup:鼠标松开时触发
另外需要明白:在一个html页面中,存在 元素对象 < HTMLObject < Document Object 这三个权限依次递增。下面针对具体的代码进行举例。
1 JS代码:
<script type="text/javascript">
window.onload=function(){
var box=document.getElementById("box");
//直接传入 box 对象
drop(box);
}
function drop(obj){
obj.onmousedown=function(event){
// IE8 中 获取鼠标点击 防止 页面ctrl+A导致功能失效
obj.setCapture && obj.setCapture();
//解决兼容性问题
event=event||window.event
//关于以下两部 请看图示
//拖拽时鼠标相对于块的X位置:event.clientX-元素.offsetLeft
//拖拽时鼠标相对于块的Y位置:event.clientY-元素.offsetTop
var l=event.clientX-obj.offsetLeft;
var t=event.clientY-obj.offsetTop;
document.onmousemove=function(event){
//解决兼容性问题
event=event||window.event;
var left=event.clientX-l;
var top=event.clientY-t;
obj.style.left=left+"px";
obj.style.top=top+"px";
}
document.onmouseup=function(){
//alert("hah");
//释放鼠标事件
document.onmousemove=null;
document.onmouseup=null;
obj.releaseCapture && obj.releaseCapture();
}
//获取鼠标点击 防止 页面ctrl+A导致功能失效
return false;
};
}
</script>
2 HTML 代码:
//这里使body极大 目的是为了测试当页面巨大的时候,拖拽是否起作用。
<body style="width:1900px;height:2000px">
//这里的 position一定要加 不然会使拖拽在改变 left top偏移量时失效
<div id="box" style="position:absolute"></div>
</body>
3 CSS代码:
<style type="text/css">
#box{
width:100px;
height:100px;
background-color:red;
position:absolute;
}
</style>
通过以上操作,可以实现一个鼠标满页面进行拖拽的滑块,希望可以帮到大家。