您的位置:首页 > Web前端 > HTML

计算鼠标至元素中心的距离

2017-09-02 11:51 302 查看
首先将一个元素定位在当前页面的中心位置(自适应),然后用mousemove 去监听鼠标,实时计算鼠标当前位置到元素中心的距离。

html

<html>
<head></head>
<body>
<a id='text'></a>
<div id='center_box'></div>
</body>
</html>


css

#center_box{
width:100px;
height:100px;
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
}


js

<script>
(function(){
/*变量解析:
txt 用来存储计算出的距离 */
var txt,$a=$('#text');
//计算函数
function calculateDistance(moveX,moveY){
//获取div 的中心点坐标
var $divx=document.documentElement.clientWidth/2;
var $divy=document.documentElement.clientHeight/2;
//鼠标在div 右侧,计算出的值是负数,所以要用abs 绝对值来转成正数
var newx=Math.abs($divx-moveX);
var newy=Math.abs($divy-moveY);
return newx>=newy?newx:newy;
}
//现在计算函数准备好了,我们来写最重要的一步,监听事件
$(document).mousemove(function(event){
var e=event || window.event;
txt=calculateDistance(e.clientX,e.clientY);
$a.text=txt;
})
})()
//window 自执行函数,实时监听,
!function(){
function divtop(){
$('#center_box').css('margin-top',(document.documentElement.clientHeight-$div[0].clientHeight)/2);
}
divtop();
}(window)
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  html 鼠标 监听