【问题标题】:Custom Cursor, modify size when click with React自定义光标,点击 React 时修改大小
【发布时间】:2023-01-24 03:46:35
【问题描述】:

我在我的 React 应用程序上制作了一个自定义光标,但我想在用户单击时为其设置动画。喜欢减小尺寸或类似的东西。光标位于我在 Index.js 文件中调用的组件中。我不知道如何制作一个更改游标类的 addlisterner 元素。如果有人想帮助我,我是网络开发的新手,我会很感激:)

这是自定义光标组件:

import React, { useRef } from 'react'

function CustomCursor() {

const cursorRef = useRef(null)

React.useEffect(() => {
    document.addEventListener('mousemove', (event)=>  {
        const {clientX, clientY} = event;
        const mouseX = clientX - cursorRef.current.clientWidth /2;
        const mouseY = clientY - cursorRef.current.clientHeight /2;
        cursorRef.current.style.transform = `translate3d(${mouseX}px, ${mouseY}px, 0)`
    })
}, [])

    return ( <div className='custom-cursor' ref={cursorRef}></div> ) }

export default CustomCursor 

详细的css类:

.custom-cursor {
  z-index: 9999;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  background-color: #8c8c8cb8;
  pointer-events: none;
  overflow: hidden;
  transform: translate(-50%, -50%);
  position: fixed;
}

我真的不知道该尝试什么:/

【问题讨论】:

    标签: css reactjs css-selectors mouse-cursor custom-cursor


    【解决方案1】:

    您可以通过将点击事件侦听器添加到 documentwindow 对象并通过添加 CSS 类或使用 HTML 元素的 JS style 属性更新光标样式来实现此目的。一段时间后,删除更改。

    单击时自定义光标样式 -

    .custom-cursor.clicked {
      width: 10px;
      height: 10px;
    }
    

    单击事件的事件侦听器 -

    const handleCursorClick = () => {
        // change the cursor styles
        cursorRef.current.classList.add("clicked");
    
        // OR make changes using the direct using JS for example
        // cursor.current.style.width = '15px'
        // cursor.current.style.height = '15px'
    
        setTimeout(() => {
          // after some time removes though changes
          cursorRef.current.classList.remove("clicked");
    
          // cursor.style.width = '20px'  <-- base style
          // cursor.style.height = '20px' <-- base style
        }, 100);
      };
    

    【讨论】:

      猜你喜欢
      • 2013-09-15
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 2020-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多