Javascript鼠标移动函数显示元素未按预期工作



我正在尝试获取一个mousemove函数来显示当鼠标在特定div内移动鼠标时创建的自定义光标元素。自定义光标是我希望它出现在div 中的绝对定位的div。我看到的奇怪事情是我可以从开发人员工具中看到它实际上正在工作,但自定义光标实际上并没有显示。但是,如果我将自定义光标div 移动到我希望它进入并进入主体的div 之外,它显示正常。

我知道这一定是我的简单错误,但我看不到它!感谢任何建议。

let customCursor = document.querySelector('.custom-cursor');
const section2 = document.querySelector('.section2');
section2.addEventListener('mousemove', function(e) {
  customCursor.classList.add('active');
  customCursor.setAttribute("style", "top:" + (e.pageY) + "px; left: " + e.pageX + "px;");
});
section2.addEventListener('mouseleave', function() {
  customCursor.classList.remove('active');
});
.section {
  position: relative;
}
.section1 {
  height: 500px;
}
.section2 {
  height: 500px;
}
.custom-cursor {
  width: 50px;
  height: 50px;
  background: black;
  border-radius: 50%;
  display: none;
  position: absolute;
}
.custom-cursor.active {
  display: block;
}
<body>
  <section class="section1 section">Section 1</section>
  <section class="section2 section">Section 2
    <div class="custom-cursor"></div>
  </section>
</body>

像@Titus评论一样,您可以将CSS与cursor一起使用。

但是,如果您使用需要跟踪鼠标相对于section2的位置的 JS 来实现它,则需要减去section2元素左右和顶部偏移量,然后减去光标宽度和高度的一半以使光标居中:

let customCursor = document.querySelector('.custom-cursor');
const section2 = document.querySelector('.section2');
section2.addEventListener('mousemove', function(e) {
  customCursor.classList.add('active');
   customCursor.setAttribute("style", "top:" + (e.pageY - section2.offsetTop - (customCursor.offsetWidth/2) ) + "px; left: " + (e.pageX - section2.offsetLeft - (customCursor.offsetHeight/2)) + "px;");
});
section2.addEventListener('mouseleave', function() {
  customCursor.classList.remove('active');
});
.section {
  position: relative;
}
.section1 {
  height: 500px;
}
.section2 {
  height: 500px;
}
.custom-cursor {
  width: 50px;
  height: 50px;
  background: black;
  border-radius: 50%;
  display: none;
  position: absolute;
}
.custom-cursor.active {
  display: block;
}
<body>
  <section class="section1 section">Section 1</section>
  <section class="section2 section">Section 2
    <div class="custom-cursor"></div>
  </section>
</body>

position: absolute

相对于父项,如果父项具有

position:relative

因此,为了在 section2 中拥有正确的位置,您需要使用 e.layerYe.layerX 而不是 e.pageYe.pageX,因为它们基于屏幕的左上角。 e.layerYe.layerX相对于 mouseevent 附加到的容器。

试试这个: https://jsfiddle.net/42kq1w8m/9/

最新更新