我编写了一些JS函数,通过单击按钮来更改bg图像,然后再次单击按钮时返回到原始的bg。下面是我的JS。
const nextBackgroundImageUrl = {
"url('../images/pexels_bg.jpeg')": "url('/images/bbyshrk.jpg')",
"url('../images/bbyshrk.jpg')": "url('/images/pexels_bg.jpeg')"
}
function changeImg() {
const currentBackgroundUrl = document.body.style.backgroundImage;
console.log("current bg url:" + currentBackgroundUrl);
document.body.style.backgroundImage = nextBackgroundImageUrl[currentBackgroundUrl];
}
在console.log中,“当前bg网址”之后我什么也没得到,因此currentBackgroundUrl没有获取bg图像。我使用错误的样式属性来获取img吗?我需要网址。
谢谢!
function changeBG() {
document.body.classList.contains("alt") ? document.body.classList.remove("alt") : document.body.classList.add("alt");
}
body {
background-image: url('https://images.pexels.com/photos/531880/pexels-photo-531880.jpeg?auto=compress&cs=tinysrgb&h=350');
background-repeat: no-repeat;
background-size: cover;
transition: all 1s ease-in;
}
body.alt {
background-image: url('https://images.pexels.com/photos/2265082/pexels-photo-2265082.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260');
}
<button onClick="changeBG()">Change BG</button>