2 回答
TA贡献1817条经验 获得超14个赞
不要使用内联样式设置背景(这通常被认为是最后的手段,因为它很难覆盖并且因为它使呈现的 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>
TA贡献1799条经验 获得超8个赞
当您使用 querySelectorAll 选择元素时,即使没有元素与选择器匹配,它也会返回一个 HTML 集合(节点列表),因此要访问它,您应该像这样将其作为数组元素访问
var image1 = document.querySelectorAll(".image1");
image1[0].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)";
});
或者您可以像这样使用 querySelector
var image1 = document.querySelector(".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)";
});
添加回答
举报