【问题标题】:Trying to add a mouseenter and mouseleave function to an image尝试向图像添加 mouseenter 和 mouseleave 函数
【发布时间】:2020-08-28 04:07:18
【问题描述】:

我正在尝试向图像添加 mouseenter 和 mouseleave 函数。我希望图像的 src 在 mouseenter 发生时改变,并在 mouseleave 发生时改变回来。现在图像的 src 目前正在 dom 中更改,但图像没有更改。图像上还有一个 srcset 属性,我尝试在 mouseenter 上进行更改,但我只是得到一个空白的白色背景。这是我的代码:

document.addEventListener("DOMContentLoaded", function () {
  const img = document.querySelector("#div1 img");

  img.addEventListener("mouseenter", function () {
    img.src = "https://images.unsplash.com/photo-1542826045-6a629cdc8b1f?ixlib=rb-1.2.1&auto=format&fit=crop&w=1389&q=80";
    img.setAttribute('srcset', 'https://images.unsplash.com/photo-1542826045-6a629cdc8b1f?ixlib=rb-1.2.1&auto=format&fit=crop&w=1389&q=80')
  })

  img.addEventListener("mouseleave", function () {
    img.src = "https://images.unsplash.com/photo-1598104514968-1bb2c80c5994?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=675&q=80";
    img.setAttribute('srcset', 'https://images.unsplash.com/photo-1598104514968-1bb2c80c5994?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=675&q=80');
  })
})

【问题讨论】:

标签: javascript mouseenter mouseleave


【解决方案1】:

在此处添加它而不是 cmets,因为该建议有点冗长。

您的图片路径未获取任何图片。我尝试了其他一些有效的图像并且它有效。见下面的sn-p

img{
 height: 200px;

}
<div id="div1">
  <img src="https://images.unsplash.com/photo-1598382569639-d28c1a9a21da?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=934&q=80" />
</div>

<script>

document.addEventListener("DOMContentLoaded", function () {
  const img = document.querySelector("#div1 img");

  img.addEventListener("mouseenter", function () {
    img.src = "https://images.unsplash.com/photo-1598557334954-f501396943e7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=934&q=80";
    
  })

  img.addEventListener("mouseleave", function () {
    img.src = "https://images.unsplash.com/photo-1598382569639-d28c1a9a21da?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=934&q=80g";
   
  })
})
</script>

【讨论】:

  • 谢谢辛巴。原始 html 和 js 工作正常。我认为这与我使用的 WP 主题有关。
猜你喜欢
  • 1970-01-01
  • 2010-11-26
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-30
  • 1970-01-01
相关资源
最近更新 更多