在按钮内包含元素

在我的 React 项目中,我有一个使用 Javascript 跟随光标的球,并且只有当它使用这个 css 块悬停在按钮元素上时才会出现:


#app button:hover + .ball {

  display: block;

}


.ball {

  display: none;

}

它目前有效,但是我正在尝试找出一种将球包含在按钮内的方法。现在,如果您将鼠标悬停在按钮的边缘上,球就会延伸到按钮之外。


料青山看我应如是
浏览 60回答 1
1回答

元芳怎么了

如果将button和.ball元素放在某种容器 div 中,则可以overflow:hidden在容器上进行:内render:<div className="button-container">&nbsp; <button>BUTTON</button>&nbsp; <div ref={ballRef} className="ball"></div></div>在样式表中:.button-container {&nbsp; position: relative;&nbsp; display: inline-block;&nbsp; overflow: hidden;}let mouseX = 0let mouseY = 0let ballX = 0let ballY = 0let speed = 0.2const Page = () => {&nbsp; const ballRef = React.useRef(null)&nbsp; const animate = React.useCallback(() => {&nbsp; &nbsp; if (ballRef && ballRef.current) {&nbsp; &nbsp; &nbsp; let distX = mouseX - ballX&nbsp; &nbsp; &nbsp; let distY = mouseY - ballY&nbsp; &nbsp; &nbsp; ballX = ballX + distX * speed&nbsp; &nbsp; &nbsp; ballY = ballY + distY * speed&nbsp; &nbsp; &nbsp; ballRef.current.style.left = ballX + "px"&nbsp; &nbsp; &nbsp; ballRef.current.style.top = ballY + "px"&nbsp; &nbsp; }&nbsp; &nbsp; requestAnimationFrame(animate)&nbsp; }, [ballRef, mouseX, mouseY, ballX, ballY])&nbsp; React.useEffect(() => {&nbsp; &nbsp; const onMouseMove = event => {&nbsp; &nbsp; &nbsp; mouseX = event.pageX&nbsp; &nbsp; &nbsp; mouseY = event.pageY&nbsp; &nbsp; }&nbsp; &nbsp; document.addEventListener("mousemove", onMouseMove)&nbsp; &nbsp; animate()&nbsp; &nbsp; return () => document.removeEventListener("mousemove", onMouseMove)&nbsp; }, [])&nbsp;&nbsp;&nbsp;return (&nbsp; &nbsp;<React.Fragment>&nbsp; &nbsp; &nbsp;<div className="button-container">&nbsp; &nbsp; &nbsp; &nbsp;<button>BUTTON</button>&nbsp; &nbsp; &nbsp; &nbsp;<div ref={ballRef} className="ball"></div>&nbsp; &nbsp; &nbsp;</div>&nbsp; &nbsp; &nbsp;<div class="divs"></div>&nbsp; &nbsp; &nbsp;<div class="divs"></div>&nbsp; &nbsp;</React.Fragment>&nbsp; );}ReactDOM.render(<Page/>, document.querySelector('#app'));#app button:hover + .ball {&nbsp; display: block;}.button-container {&nbsp; position: relative;&nbsp; display: inline-block;&nbsp; overflow: hidden;}.ball {&nbsp; display: none;}button{&nbsp; background-color: green;&nbsp; padding: 20px;}.ball {&nbsp; background-color: red;&nbsp; width: 26px;&nbsp; height: 26px;&nbsp; border-radius: 50%;&nbsp; position: absolute;&nbsp; top: 0;&nbsp; left: 0;&nbsp; transform: translate(-50%, -50%);&nbsp; mix-blend-mode: screen;&nbsp; transition: transform 0.4s, border 0.4s;&nbsp; border: 2px solid transparent;&nbsp; pointer-events: none;}.divs{&nbsp; background-color: gray;&nbsp; padding:20px;&nbsp; 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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript