div拖动
程序员文章站
2022-07-03 23:17:41
...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>拖动div</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<style type="text/css">
*{
margin: 0px;
padding: 0px;
}
body{
position: relative;
}
#click{
background-color: red;
position: absolute;
top: 0px;
left: 0px;
height: 50px;
width: 20%;
}
</style>
</head>
<body>
<p id="click">点击</p>
</body>
<script type="text/javascript">
//拖动div
var drags=document.getElementById("click");
drags.onmousedown=function(e){
e=e||window.event;
var xx=e.layerX|| e.offsetX; //相对当前坐标系的border左上角开始的坐标
var yy=e.layerY|| e.offsetY;
/* var dw=document.body.clientWidth;
var dh=document.body.clientHeight;*/
//设置捕获范围 //兼容浏览器
/* if(drags.setCapture){
drags.setCapture();
}else if(window.captureEvents){
window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP)
}*/
document.onmousemove =function(e){
var ev=e||window.event;
var x=ev.pageX||ev.clientX; //相对整个页面的坐标
var y=ev.pageY||ev.clientY;
var tx=x-xx;
var ty=y-yy;
var bw= window.innerWidth-drags.offsetWidth;
var bh= window.innerHeight-drags.offsetHeight;
if(drags.offsetLeft>=0 && drags.offsetLeft<= bw && drags.offsetTop>=0 && drags.offsetTop<=bh){
drags.style.left=tx+"px";
drags.style.top=ty+"px";
}
if(drags.offsetLeft<0){
drags.style.left=0+"px";
}
if(drags.offsetLeft>bw){
drags.style.left=bw+"px";
}
if(drags.offsetTop<0){
drags.style.top=0+"px";
}
if(drags.offsetTop>bh){
drags.style.top=bh+"px";
}
}
document.onmouseup=function(){
//取消捕获范围 //兼容浏览器
/* if(drags.releaseCapture){
drags.releaseCapture();
}else if(window.captureEvents){
window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP)
}*/
//清除事件
document.onmousemove=null;
document.onmouseup=null;
}
}
//手机版
// e.preventDefault();//阻止触摸时浏览器的缩放、滚动条滚动
drags.addEventListener("touchstart",function(e){
var x= e.touches[0].pageX; //触点开始位置
var y= e.touches[0].pageY;
var drx=drags.offsetLeft; //开始,div与容器的边距
var dry=drags.offsetTop;
document.addEventListener("touchmove",function(e){
var tx=drx+(e.touches[0].clientX-x); //e.touches[0] 触点移动的位置
var ty=dry+(e.touches[0].clientY-y);
var dw=window.innerWidth-drags.offsetWidth;
var dh=window.innerHeight-drags.offsetHeight;
if(tx>=0 && tx<=dw && ty>=0 && ty<=dh){
drags.style.left=tx+"px";
drags.style.top=ty+"px";
}
if(tx<0){
drags.style.left=0+"px";
}
if(tx>dw){
drags.style.left=dw+"px";
}
if(ty<0){
drags.style.top=0+"px";
}
if(ty>dh){
drags.style.top=dh+"px";
}
})
document.addEventListener("ontouchend",function(){
})
})
</script>
</html>
转载于:https://my.oschina.net/u/2524300/blog/602544