按钮背景图像切换不返回原始背景图像
function myFunction() {
var element = document.body;
element.classList.toggle("light-mode");
var btndrk = document.getElementById('drk');
if (btndrk.style.backgroundImage === "url('https://assets.codepen.io/1462889/moon.svg')") {
onlick(btndrk.style.backgroundImage = "url('https://assets.codepen.io/1462889/sun.svg')");
} else {
btndrk.style.backgroundImage = "url('https://assets.codepen.io/1462889/moon.svg')";
}
}
#drk {
position: relative;
height: 70%;
width: 3.3%;
top: 15%;
background-color: rgb(105, 50, 255);
color: white;
font-family: 'Advent Pro', sans-serif;
border-radius: 5px;
background-image: url('https://assets.codepen.io/1462889/moon.svg');
background-size: 45% 45%;
background-repeat: no-repeat;
background-position: center;
border-radius: 50%;
border: none;
transition: all 200ms linear;
box-shadow: 0 0 1vw rgba(255,235,167,.25);
}
<button id="drk" onclick="myFunction()"></button>
我想让原始背景图像在第二次点击中返回,并在第三和第四点上进行Sun.svg显示。目前,原始的背景图像显示了我刷新页面时显示的,但是一点击后,它更改为sun.svg,并且不会更改。我希望它在两者之间切换。
function myFunction() {
var element = document.body;
element.classList.toggle("light-mode");
var btndrk = document.getElementById('drk');
if (btndrk.style.backgroundImage === "url('https://assets.codepen.io/1462889/moon.svg')") {
onlick(btndrk.style.backgroundImage = "url('https://assets.codepen.io/1462889/sun.svg')");
} else {
btndrk.style.backgroundImage = "url('https://assets.codepen.io/1462889/moon.svg')";
}
}
#drk {
position: relative;
height: 70%;
width: 3.3%;
top: 15%;
background-color: rgb(105, 50, 255);
color: white;
font-family: 'Advent Pro', sans-serif;
border-radius: 5px;
background-image: url('https://assets.codepen.io/1462889/moon.svg');
background-size: 45% 45%;
background-repeat: no-repeat;
background-position: center;
border-radius: 50%;
border: none;
transition: all 200ms linear;
box-shadow: 0 0 1vw rgba(255,235,167,.25);
}
<button id="drk" onclick="myFunction()"></button>
I want to have the original background image come back on the second click and the sun.SVG show on the third and so-on and so-fourth. Right now the original background-image shows when I refresh the page but after one click it changes to sun.SVG and does not change back. I want it to toggle between the two.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无需在JS中进行图像更改。
JS可以简单地:
对于CSS部分,您需要添加:
You don't need to do the image change in JS.
The JS can simply be:
And for the CSS part you need to add: