计算鼠标至元素中心的距离
2017-09-02 11:51
302 查看
首先将一个元素定位在当前页面的中心位置(自适应),然后用mousemove 去监听鼠标,实时计算鼠标当前位置到元素中心的距离。
html
css
js
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>
相关文章推荐
- jquery计算鼠标和指定元素之间距离的方法
- jquery计算鼠标和指定元素之间距离的方法
- HDU:4707 Pet(并查集+某元素到根节点的距离计算)
- 创建函数计算目标元素到浏览器窗口的距离
- 关于js拖拽功能,拖拽元素的position:fixed;left:0;right:0;样式引起左右拖动元素会出现落后鼠标移动距离的问题
- 计算元素距离浏览器左边的距离
- 鼠标越接近图像,图像会越大,它会很聪明的判断出图像中心距鼠标的距离
- 无定位父元素时offsetParent为body,但是offsetTop/offsetLeft计算距离从html开始
- js计算鼠标当前相对于某个元素的位置
- 计算鼠标按下松开之间的距离---- 在路上(30)
- Matlab Tricks(十八)—— 矩阵间元素距离的计算
- [C#, WPF] 根据鼠标距离窗口中心的距离设置其背景色
- 深入理解盒子模型,计算各个元素之间的距离
- js 计算页面某个元素距离页面顶端的距离
- [2016/11/30]项目V1.0:计算两个氨基酸之间的中心碳原子距离和最近距离
- 华为机试---计算字符串的距离
- HDU_2001——计算两点之间的距离
- 经纬度与距离米的计算
- Java经纬读坐标的距离计算
- 鼠标点击屏幕两点出现距离数字(算是测距),代码(3D)