尝试向图像添加 mouseenter 和 mouseleave 函数

Trying to add a mouseenter and mouseleave function to an image

我正在尝试向图像添加 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');
  })
})

在这里添加它而不是评论,因为建议有点冗长。

您的图片路径未获取任何图片。我尝试了一些其他有效的图像并且它起作用了。请参阅下面的代码段

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>