为了账号安全,请及时绑定邮箱和手机立即绑定

跟随鼠标移动和滚动的元素

跟随鼠标移动和滚动的元素

qq_花开花谢_0 2021-12-23 19:27:50
我正在尝试编写一些 Vanilla Javascript 来使元素跟随我的鼠标移动。我使用了 clientX、clientY 和 mousemove 事件使其跟随,但是当我滚动页面时,元素不会随鼠标移动。我想也许我需要使用滚动事件,但我正在努力使它工作。任何帮助都会很棒,谢谢!document.addEventListener('mousemove', (e) => {    const mouseFollow = document.getElementById('mouse-follow');    const x = e.clientX - 25; //-25 to center div over mouse    const y = e.clientY - 25;     mouseFollow.style.top = `${y}px`;    mouseFollow.style.left = `${x}px`;})
查看完整描述

2 回答

?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

使用position: fixed;. clientX/Y是相对于视口的,CSS 位置也是如此fixed。

缓存您的选择器,无需在每次鼠标移动时查询 DOM 元素

const mouseFollow = document.getElementById('mouse-follow');


document.addEventListener('mousemove', (e) => {

  mouseFollow.style.cssText = `

    left: ${e.clientX - 25}px;

    top:  ${e.clientY - 25}px;

  `;

});

body {

  height: 200vh;

}


#mouse-follow {

  position: fixed;

  left: 0;

  top:0;

  padding: 25px;

  background: red;

}

<div id="mouse-follow"></div>


查看完整回答
反对 回复 2021-12-23
?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

我怀疑您缺少的是元素必须具有绝对位置。这是一个有效的解决方案:


document.addEventListener('mousemove', (e) => {


   const mouseFollow = document.getElementById('mouse-follow');

   const x = e.clientX - 25; //-25 to center div over mouse

   const y = e.clientY - 25; 

   console.log(x);

    

   mouseFollow.style.top = `${y}px`;

   mouseFollow.style.left = `${x}px`;

})

#mouse-follow{

  background: orange;

  position: absolute;

}

<span id=mouse-follow>*</span>


查看完整回答
反对 回复 2021-12-23
  • 2 回答
  • 0 关注
  • 245 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号