【问题标题】:changing image in different div on hover悬停时更改不同div中的图像
【发布时间】:2022-02-09 17:57:35
【问题描述】:

我有一个包含 6 个元素的页面,每行 3 个元素。我的目标是在将带有id=a 的div 悬停在第一行时,用第二行的id=b 更改div 中的图像。下面是我的 HTML。

主页.html

{% block body %}

<div class="container-fluid">

<!--ROW 1-->
    <div class="row w-100">
        <div class="card col-4 mobile-fly-me-section sidebar-color">
              <div class="text-uppercase home-fly">Lorem Ipsum</div>
          </div>
          <div class="card col-4 hal-section justify-content-between p-3" id="a" onmouseover="chbg('red')" onmouseout="chbg('white')">
              <h5 class="card-title home text-uppercase">header</h5>
              <a href="{% url 'main' %}" class="border-0 text-uppercase home stretched-link text-decoration-none">GO <img class="arrow" src="{% static 'assets/main/arrow.svg' %}"></a>
          </div>
          <div class="col-4 border d-flex flex-column min-vh-25 justify-content-end align-items-bottom p-3 home">Lorem ipsum</div>
    </div>
<!--END ROW 1-->

<!--ROW 2-->
<div class="row w-100">
    <div class="card col-4 mobile-fly-me-section text-uppercase home" id="b">
        <img src="{% static 'assets/graphics/graphic 01.svg' %}" width="75%"> <!-- before hover-->
        <img src="{% static 'assets/graphics/graphic 02.svg' %}" width="75%"> <!-- after hover-->
      </div>
        <div class="col-4 border d-flex flex-column min-vh-25 justify-content-end align-items-bottom p-3 home">Lorem ipsum</div>
        <div class="col-4 border d-flex flex-column min-vh-25 justify-content-between align-items-top p-3 text-uppercase home"><b>Lorem ipsum</b>
        <div> <img class="arrow" src="{% static 'assets/main/arrow.svg' %}">
        </div>
</div>
<!--END ROW 2-->

</div>

{% endblock body %}

{% block js %}
<script async src="//jsfiddle.net/YShs2/embed/"></script>
<script>
  function chbg(color) {
      document.getElementById('b').style.backgroundColor = color;
  }
</script>
{% endblock js %}

我发现solution 正在更改背景颜色,但我不确定如何切换图像(从图形 01.svg 到图形 02.svg)

【问题讨论】:

  • 要更改图像源,请使用:document.getElementById("image_id").src = 'assets/main/graphic02.svg'
  • 您可以尝试使用jQuery$("#id").attr("str", URL); 更改属性
  • 请向我们展示您已经为鼠标悬停事件编写的 JS。
  • @AHaworth 如果他需要它作为新代码怎么办?
  • @AHaworth 代码已经在问题中了

标签: javascript html jquery css django


【解决方案1】:

您可以通过与更改背景的方式类似的方式来执行此操作。您需要更新的属性是“内容”,并将其设置为“url(http://someimage.com)”

所以你会有一个类似的功能

  function changeURL(imgURL) {
    document.getElementById('b').style.content = `url(${imgURL})`;
  }

然后在 div #a 你可以有

onmouseover="changeURL(url1)" onmouseout="changeURL(url2)"

【讨论】:

  • 谢谢你的回答,我有一个问题。我应该在 id=b 的 div 中的 src 中放入什么?
  • 啊,说得好。您可以添加“空白”图像,也可以在 changeURL 中动态插入图像。这里给出了几个不同的选项stackoverflow.com/questions/5775469/… 一个选项是以下 或
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-13
相关资源
最近更新 更多