javascript - 单击事件侦听器以获取背景图像不起作用
问题描述
这是我的 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;
}
解决方案
不要使用内联样式设置背景(这通常被认为是最后的手段,因为它很难覆盖并且因为它使呈现的 HTML 变得非常混乱),而是使用 CSS 类和.classList
API 进行设置,如下所示:
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>
推荐阅读
- eclipse - 我收到错误“类
无法解析为类型” - typescript - 返回类型ORM删除突变
- scala - 如何在 Spark 数据框中使用嵌套列进行连接
- javascript - 更新系列数据结果后无法单击甘特图的(有时)类别(Y轴)
- xamarin.forms - 绑定在自定义控件的 Rg.Plugins.Popup 中不起作用
- c - 指针大小可以是 4.75 字节吗
- python-3.x - Why does my curl request work and my python3 request not work when calling a webservice?
- sql-server - 为每百万行设置一个具有 Page 值的列
- python - 有没有办法在浮点数中找到特定数字?像字符串的 find() 方法一样吗?
- python - 熊猫数据框中的非重叠滚动窗口