我正在尝试获取一个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>
发布于 2019-08-06 23:40:09
就像@Titus注释一样,你可以在cursor中使用CSS。
但是如果你使用JS实现它,需要跟踪鼠标相对于section2的位置,你将需要减去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>
发布于 2019-08-06 23:40:09
position: absolute是相对于父级的,如果父级具有
position:relative因此,为了在section2中拥有正确的位置,您需要使用e.layerY和e.layerX而不是e.pageY和e.pageX,因为它们基于屏幕的左上角。e.layerY和e.layerX是相对于鼠标事件所附加到的容器的。
https://stackoverflow.com/questions/57379178
复制相似问题