【发布时间】:2021-07-20 00:30:33
【问题描述】:
我是一个非常缺乏经验的开发人员。我正在努力寻找解决方案。我有两个具有相同类的按钮,以及一个名为 cursorFollower 的 div,它实际上遵循实际的 pageX 和 pageY 定位。上周,感谢一些人的帮助,我设法根据悬停的按钮更改了 cursorFollower 的形状。问题是我无法让它与同一类的所有按钮一起使用。有人建议我将它从 querySelector 更改为 querySelectorAll 以选择具有相同类的所有元素,但是如何知道一次悬停的是哪个元素?同样出于某种原因,在使用 codepen 时,它一直说 getBoundingClientRect 现在应该在一个函数中,它将按钮的大小和位置作为单独的变量获取。我已将所有内容都包含在一个函数中,但什么都没有发生。有人可以告诉我我做错了什么并建议我该怎么做吗?
let cursor = document.querySelector('.cursorFollower');
let button = document.querySelector('.menutext');
let buttonWidth = button.getBoundingClientRect().width;
let buttonHeight = button.getBoundingClientRect().height;
let buttonX = button.getBoundingClientRect().left;
let buttonY = button.getBoundingClientRect().top;
var onContainer = false;
const handleCursor = (e) => {
if (onContainer) {
cursor.setAttribute(
"style",
`left: ${buttonX}px;top: ${buttonY}px;width: ${buttonWidth}px;height: ${buttonHeight}px; transform: rotate(0deg); border: 1px solid #84c4b5;`
);
button.setAttribute(
"style",
`color: #84C4B5;`
);
} else {
cursor.setAttribute(
"style",
`left: width: 20px; height: 20px; transform: rotate(45deg); border: solid 1px #ffffff;`
);
cursor.style.left = e.pageX - 10 + 'px';
cursor.style.top = e.pageY - 10 + 'px';
button.setAttribute(
"style",
`color: #ffffff;`
);
}
};
document.addEventListener("mousemove", handleCursor);
button.onmouseover = () => {
onContainer = true;
};
button.onmouseleave = () => {
onContainer = false;
};
*{
margin: 0;
padding: 0;
}
.container {
position: relative;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width:100%;
height: 100vh;
background-color: #0A193E;
color: white;
font-family: sans-serif;
font-size: 20px;
}
.container2 {
position: relative;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width:100%;
height: 100vh;
background-color: green;
color: white;
font-family: sans-serif;
font-size: 20px;
}
.menutext {
padding: 10px 20px;
cursor: none;
transition: all 0.2s ease;
}
.cursorFollower {
width: 20px;
height: 20px;
position: absolute;
border: 2px solid white;
transition: all 0.2s ease-out;
pointer-events: none;
transform: rotate(45deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<p class="menutext">button1</p>
<p class="menutext">button2</p>
</div>
<div class="container2">
<p class="menutext">button3</p>
</div>
<div class="cursorFollower"></div>
【问题讨论】:
标签: javascript html jquery css