我当前在React项目中的光标后面有一个圆形的球。但是我只希望当光标悬停在按钮上时才显示它,而别无其他。
有什么想法要实现吗?
这里是codepen
let mouseX = 0
let mouseY = 0
let ballX = 0
let ballY = 0
let speed = 0.2
const Page = () => {
const ballRef = React.useRef(null)
const animate = React.useCallback(() => {
if (ballRef && ballRef.current) {
let distX = mouseX - ballX
let distY = mouseY - ballY
ballX = ballX + distX * speed
ballY = ballY + distY * speed
ballRef.current.style.left = ballX + "px"
ballRef.current.style.top = ballY + "px"
}
requestAnimationFrame(animate)
}, [ballRef, mouseX, mouseY, ballX, ballY])
React.useEffect(() => {
const onMouseMove = event => {
mouseX = event.pageX
mouseY = event.pageY
}
document.addEventListener("mousemove", onMouseMove)
animate()
return () => document.removeEventListener("mousemove", onMouseMove)
}, [])
return (
<>
<button>BUTTON</button>
<div ref={ballRef} className="ball"></div>
<div class="divs"></div>
<div class="divs"></div>
</>
);
}
答案 0 :(得分:0)
将此内容添加到CSS的开头将提供您正在寻找的基本效果:
#app button:hover + .ball {
display: block;
}
.ball {
display: none;
}
此处的第一行假设.ball将在按钮之后立即添加到DOM中。
如果您希望将球夹在按钮内,则应重新排列React脚本中的HTML,以使.ball
div位于<button>
元素内,然后更新按钮的CSS(因为然后将球包含在按钮内,您实际上不需要上面的CSS行,但是如果保留它们,只需除去“ +”号即可。
JS中的更新部分:
return (
<>
<button>BUTTON
<div ref={ballRef} className="ball"></div>
</button>
<div class="divs"></div>
<div class="divs"></div>
</>
);
CSS中的更新部分:
button{
background-color: green;
padding: 20px;
position: relative;
overflow: hidden;
}