1 回答
TA贡献1798条经验 获得超7个赞
如果将button和.ball元素放在某种容器 div 中,则可以overflow:hidden在容器上进行:
内render:
<div className="button-container">
<button>BUTTON</button>
<div ref={ballRef} className="ball"></div>
</div>
在样式表中:
.button-container {
position: relative;
display: inline-block;
overflow: hidden;
}
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 (
<React.Fragment>
<div className="button-container">
<button>BUTTON</button>
<div ref={ballRef} className="ball"></div>
</div>
<div class="divs"></div>
<div class="divs"></div>
</React.Fragment>
);
}
ReactDOM.render(<Page/>, document.querySelector('#app'));
#app button:hover + .ball {
display: block;
}
.button-container {
position: relative;
display: inline-block;
overflow: hidden;
}
.ball {
display: none;
}
button{
background-color: green;
padding: 20px;
}
.ball {
background-color: red;
width: 26px;
height: 26px;
border-radius: 50%;
position: absolute;
top: 0;
left: 0;
transform: translate(-50%, -50%);
mix-blend-mode: screen;
transition: transform 0.4s, border 0.4s;
border: 2px solid transparent;
pointer-events: none;
}
.divs{
background-color: gray;
padding:20px;
margin:20px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script>
<div id="app"></div>
添加回答
举报