【问题标题】:Change image on row hover in Reactjs在 Reactjs 中更改行悬停图像
【发布时间】:2020-11-05 03:39:40
【问题描述】:

我正在开发一个反应应用程序,要求是在行悬停时更改图像。

有多行,每行有两列(名称和图像)。要求是只在该行悬停时显示头盔图像,当它没有悬停时,它应该显示相机图像。

我可以在图像列悬停时更改图像,但如何在行悬停时更改图像?

<div class="container">
  <div> Name </div>
  <div> 
    <img src="https://img.icons8.com/material/4ac144/256/camera.png" height="30px" width="30px"/> 
    <img src="https://img.icons8.com/material/4ac144/256/user-male.png" height="30px" width="30px"/>
</div>
</div>


.container{
  display: flex;
  justify-content: space-around;
  width: 100%;
  height: 100px;
  border: 2px solid black;
}
.container:hover {
  background-color: yellow;
}

【问题讨论】:

  • 您发布的 html 中的“行”是什么?
  • @RobMoll 只是图像和名称的父容器

标签: javascript html jquery css reactjs


【解决方案1】:

如果您想在将鼠标悬停在其父 .container 上时更新图像元素的 src 属性,则必须使用 JavaScript。您可以使用 jQuery 来实现您的目标:

$('.container').hover(
    () => { // on mouse over
        $(this).find('img').attr('src', '[your new image url]')
    },
    () => { // on mouse out
        $(this).find('img').attr('src', '[your old image url]')
    }
);

看看这个小提琴,以更好地了解正在发生的事情: https://jsfiddle.net/g9p834fb/

编辑:这是在您更新问题之前提交的。

要简单地替换行中的图像,您只需更新 CSS。请参阅此小提琴以了解所需的更改:https://jsfiddle.net/g9p834fb/1/

要点是您可以根据容器的状态(即悬停,未悬停)为图像定义样式

这是更新后的 html 的样子:

    <img src="https://img.icons8.com/material/4ac144/256/camera.png" height="30px" width="30px" class="default-image"/> 
    <img src="https://img.icons8.com/material/4ac144/256/user-male.png" height="30px" width="30px" class="hover-image"/>

如您所见,我们使用两个类来区分两种状态。

然后你只需要添加这两种样式:

.container .default-image,
.container:hover .hover-image{
  display: block;
}

.container .hover-image,
.container:hover .default-image{
  display: none;
}

应该可以达到你想要的效果。

【讨论】:

  • 非常感谢 Romi,但我们如何在 reactjs 中实现这一点?实际上 jQuery 方法在我的情况下不起作用
  • @newbie 我已经更新了我的答案。请看一下,如果它是您要找的,请告诉我。
  • 感谢您的帮助。不完全是我正在寻找的。我无法更好地解释它,所以没关系
  • @newbie 但这正是您在问题中所描述的。 The requirement is to show helmet image only when the row is hovered and when it is not hovered, it should show the camera image. 这就是小提琴所展示的。
  • 其实问题出在我的头上,我无法解释这个问题。我正在做一个实际问题的演示,然后我会重新发布
【解决方案2】:

不需要任何 js 来实现这一点,只需像这样简单的 css 悬停:

.container {
  display: flex;
  justify-content: space-around;
  width: 100%;
  height: 100px;
  border: 2px solid black;
}

.show-on-hover {
  display: none;
}

.container:hover {
  background-color: yellow;
}

.container:hover .show-on-hover {
  display: block;
}

.container:hover .hide-on-hover {
  display: none;
}
<div class="container">
  <div> Name </div>
  <div>
    <img class="hide-on-hover" src="https://img.icons8.com/material/4ac144/256/camera.png" height="30px" width="30px" />
    <img class="show-on-hover" src="https://img.icons8.com/material/4ac144/256/user-male.png" height="30px" width="30px" />
  </div>
</div>

【讨论】:

  • 这与我提出的解决方案相同。在更新初始问题后,我更新了我的答案。您还可以简化样式。
  • 抱歉,我感觉不到您要编辑答案
  • 感谢 Nico 的帮助 :)
猜你喜欢
  • 2012-03-13
  • 2018-07-20
  • 1970-01-01
  • 1970-01-01
  • 2023-01-11
  • 2021-01-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多