首页 > 解决方案 > 在 ReactJS 中悬停图像的特定部分时如何更改鼠标光标?

问题描述

我在 ReactJS 中创建了一个应用程序

HTML

<div id="root"></div>

反应 JS

function MouseCursor() {
    return(
        
            <div>
                <img src='https://usabilla.com/graphics/resources/usabilla-logo.png' style={{cursor: "wait", backgroundRepeat: "no-repeat", height: "160px",  width:"80%"}} />
                
                <p>Right Now the cursor image changes when overing the image</p>
            </div>
    
    )
}

ReactDOM.render(<MouseCursor />, document.querySelector("#root"))

这段代码的 jsfiddle 是:

https://jsfiddle.net/vewzyo2x/

当我悬停图像时,光标会发生变化,但只有当图像的某个部分悬停时,我才需要更改鼠标的光标,如下图所示 在此处输入图像描述

只有当鼠标悬停在上图所示的圆圈上时,我才需要更改图像的光标。我怎样才能做到这一点?

标签: javascriptcssreactjs

解决方案


如果您在“blob”为圆形时测量图像上的各种距离,您将获得 CSS 来计算 blob 相对于整个图像的尺寸和位置(以百分比计)。当图像被拉伸时,blob 将相应地拉伸。

在这个香草 JS 片段中,徽标图像显示为 div 的背景,blob 是它的子 div。这省去了在 DOM 中添加另一个不会增加意义的 div 的麻烦。

测量只是用尺子进行的(单位无关紧要)

.usabilla {
  --h: 8.75;
  /* image height measured by a ruler */
  --w: 19.4;
  /* image width */
  --top: 1.5;
  /* position of the blob */
  --left: 11.7;
  --diam: 2;
  /* diameter of the blob (when the blob was circular) */
  width: 80%;
  height: 160px;
  background-image: url(https://usabilla.com/graphics/resources/usabilla-logo.png);
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-position: center center;
  position: relative;
}

.blob {
  cursor: wait;
  height: calc(var(--diam) / var(--h) * 100%);
  width: calc(var(--diam) / var(--w) * 100%);
  position: absolute;
  top: calc(var(--top) / var(--h) * 100%);
  left: calc(var(--left) / var(--w) * 100%);
  background-color: transparent;
  border-radius: 50%;
}
<div class="usabilla">
  <div class="blob"></div>
</div>


推荐阅读