为了账号安全,请及时绑定邮箱和手机立即绑定

在按钮内包含元素

在按钮内包含元素

料青山看我应如是 2022-06-05 16:41:39
在我的 React 项目中,我有一个使用 Javascript 跟随光标的球,并且只有当它使用这个 css 块悬停在按钮元素上时才会出现:#app button:hover + .ball {  display: block;}.ball {  display: none;}它目前有效,但是我正在尝试找出一种将球包含在按钮内的方法。现在,如果您将鼠标悬停在按钮的边缘上,球就会延伸到按钮之外。
查看完整描述

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>


查看完整回答
反对 回复 2022-06-05
  • 1 回答
  • 0 关注
  • 59 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信