鼠标onmousemove onmouseup onmousedown事件

本文详细介绍了如何在网页中实现鼠标跟随效果,通过监听鼠标事件,并计算光标相对于目标元素的位置,实现在整个页面中拖动面板的功能。具体包括事件处理、坐标计算以及面板定位的实现过程。

鼠标跟随:

鼠标事件在所有的浏览器里都支持,鼠标的坐标保存在clientX和 clientY中(水平和垂直距离坐标,不包括页面滚动距离)

<script type="text/javascript">

/*拖动面板的时候会以面板左上角坐标为参考系
*要保证光标在移动完之后仍然在面板里的绝对位置时
*需要把光标在面板的绝对距离算出来
*再将光标在整个页面的坐标减去在面板的绝对距离
*/
var oTitle = getByClass('childId','parentId');
oTitle.onmousedown=function(event){

event = event || window.event;
var pTitle = document.getElementById('parentId'),
//光标与面板顶端的距离
//clientX和clientY是该对象(一个点)光标的坐标
    disX=event.clientX-pTitle.offsetLeft,
    disY=event.clientY-pTitle.offsetTop;
//移动
document.onmousemove=function(event){
  event = event||window.event;
  fnMove(event,disX,disY);
 }
//释放
document.onmouseup=function(){
   document.onmousemove=null;
  document.onmouseup=null;
}
}

var oClose=document.getElementById('close_btn');
 oClose.onclick=function(){
 document.getElementById('parentId).style.display='none';

function fnMove(e,posX,posY){
var oDrag= document.getElementById('parentId');
var l=e.clientX-posX,//面板左上角的X坐标
    r=e.clientY-posY,//面板左上角的Y坐标
    winW=document.documentELement.childWidth||document.body.childwidth,//屏幕宽度
    winH=document.documentELement.childHeight||document.body.childheight,//屏幕高度
  maxW=winW-oDrag.offsetWidth,//可移动的最大宽度
  maxH=winH-oDrag.offsetHeight;//可移动的最大高度

if(l<0){
  l=0;//左边不要超出范围
}else if(l>maxW){
  l=maxW;//右边不要超出范围
}
if(r<0){
  r=0;//左边不要超出范围
}else if(r>maxH){
  r=maxH;//右边不要超出范围
}

//给面板设置一个规格
oDrag.style.left=l+'px';
oDrag.style.top=r+'px';
}

onmousedown是针对鼠标
onmousemove onmouseup是针对整个页面,鼠标元素在整个页面移动


</script>

 

onblur事件:鼠标失去焦点

onfocus事件:鼠标获得焦点

 

转载于:https://www.cnblogs.com/tangwaikei/articles/4415511.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值