实现这一效果掌握关键一点,以下图示
mistop 与misleft跟随鼠标移动但保持不变
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
div{
width: 200px;
height: 200px;
border: 2px red solid;
background: blue;
position: absolute;
}
</style>
<script type="text/javascript">
window.onload=function(){
var odiv=document.getElementById('adiv');
document.onmousedown=function(ev){//点击时触发
var eve=ev||event
var mistop=eve.clientY-odiv.offsetTop;//鼠标点击位置与div上边框距离
var misleft=eve.clientX-odiv.offsetLeft;//鼠标点击位置与div左边框距离
document.onmousemove=function(ev){ //鼠标移动时触发
var eve=ev||event;
var Left=eve.clientX-misleft;//自己画个图吧,你会更加清晰
var Top=eve.clientY-mistop;
odiv.style.left=Left+'px';
odiv.style.top=Top+'px';
if(Left<0){ //下面四个选择句的作用就是防止div框出界
odiv.style.left=0+'px';
}
else if((document.documentElement.clientWidth-odiv.offsetLeft)<odiv.offsetWidth){
odiv.style.left=document.documentElement.clientWidth-odiv.offsetWidth+'px';
}
if(Top<0){
odiv.style.top=0+'px';
}
else if((document.documentElement.clientHeight-odiv.offsetTop)<odiv.offsetHeight){
odiv.style.top=document.documentElement.clientHeight-odiv.offsetHeight+'px';
}
}
document.onmouseup=function ()//停止点击触发事件,关掉上面两个效果
{
document.onmousemove=null;
document.onmouseup=null;
};
}
}
</script>
<body>
<div id="adiv">
</div>
</body>
</html>
本文原创,如有发现错误或疑问,可以联系我,谢谢支持哈