首页 > 解决方案 > 单击事件侦听器以获取背景图像不起作用

问题描述

这是我的 image1 课程。单击此按钮时,我想更改背景图像。

<li class="sidebar-element">
                    <div class="image1">
                        <i class="fa fa-home" aria-hidden="true"></i> 
                        <span>Image 1</span>
                        <hr>
                        <hr id="second">
                    </div>
                </li>

这是同一文件中的 Javascript 代码。

<script type="text/javascript">
        var image1 = document.querySelectorAll(".image1");
image1.addEventListener("click", function(){
            document.body.style.backgroundimage = "url(https://images.unsplash.com/photo-1582392487150-b0bc00f92e28?ixlib=rb-                                   1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60)";
        });

我有一个在我的 css 文件中定义的原始背景图像。

body{
font-family: 'Open Sans', sans-serif;
font-size: 18px;
font-weight: 300;
color: white;
overflow-x: hidden;
height: 100%;
background: #222222;
background-image: url("https://images.unsplash.com/photo-1582392487150-b0bc00f92e28?ixlib=rb-                                   1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60");
background-repeat: no-repeat;
background-size: cover;
position: relative;

}

标签: javascripthtmljquerycss

解决方案


不要使用内联样式设置背景(这通常被认为是最后的手段,因为它很难覆盖并且因为它使呈现的 HTML 变得非常混乱),而是使用 CSS 类和.classListAPI 进行设置,如下所示:

document.querySelector(".image1").addEventListener("click", function(){
  document.body.classList.add("replacedBodyBackground");
});
body{
  font-family: 'Open Sans', sans-serif;
  font-size: 18px;
  font-weight: 300;
  color: white;
  overflow-x: hidden;
  height: 100%;
  background: #222222;
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;
  background-image: url("https://www.doublemesh.com/wp-content/uploads/2016/06/Paradise-Beach-desktop-wallpaper.jpg");
}

.replacedBodyBackground {
  background-image: url("https://i.dlpng.com/static/png/3872255-31-beach-backgrounds-psd-jpeg-png-free-premium-templates-beach-png-background-585_329_preview.webp");
}
<div class="image1">
   <i class="fa fa-home" aria-hidden="true"></i> 
   <span>Image 1</span>
   <hr>
   <hr id="second">
</div>


推荐阅读