既完美又可爱的拖拽(原生js)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style>
#dragme{
position: absolute;
top: 0;
left: 0;
}
</style>
<body>

<div id="dragme">
<img src="image/icon.png" alt=""/>

</div>

</body>
<script>

window.onload=function(){
var oDiv=document.getElementById("dragme");
var x=0;
var y=0;
oDiv.onmousedown=function(ev){
var oEvent=ev||event;
//鼠标的横坐标减去div的offsetLeft
x=oEvent.clientX-oDiv.offsetLeft;
//鼠标的纵坐标减去div的offsetTop
y=oEvent.clientY-oDiv.offsetTop;
document.onmousemove=function(ev){
var oEvent=ev||event;
var left=oEvent.clientX-x;
var right=oEvent.clientY-y;
//判断左边是否过界
if(left<0){
left=0;
}
//判断右边是否过界
else if(left>document.documentElement.clientWidth-oDiv.offsetWidth){
left=document.documentElement.clientWidth-oDiv.offsetWidth;
}
//判断上边是否过界
if(right<0){
right=0;
}
//判断下边是否过界
else if(right>document.documentElement.clientHeight){
right=document.documentElement.clientHeight-oDiv.offsetHeight;
}
oDiv.style.left=left+"px";
oDiv.style.top=right+"px";
}
document.onmouseup=function(){
//清空document的事件
document.onmousemove=null;
document.onmouseup=null;
}
//解决低版本火狐bug,干掉系统默认
return false;
}
}

</script>
</html>

下面是我的图片,一个可爱的小星星


原文地址:https://www.cnblogs.com/ellenbaby/p/5999148.html