js 鼠标位置笔记
首先贴上大神的帖子链接:
https://www.cnblogs.com/rubylouvre/archive/2009/08/24/1552862.html
主要记录clientX和clientY属性,都是事件属性。
做了一个简单的效果:
js 代码:
var test1 = document.querySelector('#test1'); var test2 = document.querySelector('#test2'); var container = document.querySelector('#container'); container.addEventListener('mousemove', function(e){ test1.style.left = (150+ 70 - e.clientX/10)+'px'; test1.style.top = (150+ 50 - (e.clientY+document.documentElement.scrollTop)/10)+'px'; }); container.addEventListener('mousemove', function(e){ test2.style.left = (100 +46.66 - e.clientX/15)+'px'; test2.style.top = (100 +33.33 - (e.clientY + document.documentElement.scrollTop)/15)+'px'; });
html 代码:
<div id="container" style="width:400px; height:400px; background: rgb(160, 160, 160); position: relative; top:300px; left: 500px;"> <div id="test1" style="z-index: 4;background:aqua; border-radius: 50%; width: 100px; height: 100px; position: absolute; left: 150px; top: 150px;"></div> <div id="test2" style="box-sizing:border-box; border: solid 30px rgb(216, 202, 122); border-radius: 50%; width: 200px; height: 200px; position: absolute; left: 100px; top: 100px;"></div> </div>
(为了方便测试直接把css写在里面了)
本来感觉挺简单的东西,但是单单用脑子老是会想错,必须拿张纸画个图才好。
需要注意的是,我使用了scrollTop 属性,是为了在页面滚动时相对位置依然不会改变。
有待跟新。。。