2 回答

TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超14個(gè)贊
不要使用內(nèi)聯(lián)樣式設(shè)置背景(這通常被認(rèn)為是最后的手段,因?yàn)樗茈y覆蓋并且因?yàn)樗钩尸F(xiàn)的 HTML 變得非?;靵y),而是使用 CSS 類(lèi)和.classList
API 進(jìn)行設(shè)置,如下所示:
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貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超8個(gè)贊
當(dāng)您使用 querySelectorAll 選擇元素時(shí),即使沒(méi)有元素與選擇器匹配,它也會(huì)返回一個(gè) HTML 集合(節(jié)點(diǎn)列表),因此要訪(fǎng)問(wèn)它,您應(yīng)該像這樣將其作為數(shù)組元素訪(fǎng)問(wèn)
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)";
});
添加回答
舉報(bào)