gpt4 book ai didi

Javascript mousemove 函数显示元素未按预期工作

转载 作者:行者123 更新时间:2023-12-02 23:10:33 25 4
gpt4 key购买 nike

我试图获取一个 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一起使用。

但是如果你用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>

关于Javascript mousemove 函数显示元素未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57379178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com