[英]How do I unset and reset a Background Image via JavaScript Function?
I want to be able to change my website from a light theme to a dark theme via a button click.我希望能够通过单击按钮将我的网站从浅色主题更改为深色主题。 The background Image is also supposed to change.背景图像也应该改变。 When I click on the button the image does change, but once I scroll down a bit the light-theme-image reappears underneath it.当我点击按钮时,图像确实发生了变化,但是一旦我向下滚动一点,浅色主题图像就会重新出现在它的下方。 I've tried setting the background Image property to none and resetting it to the picture I want to, but that hasn't helped.我尝试将背景图像属性设置为无并将其重置为我想要的图片,但这并没有帮助。 Also tried resetting the backgroundAttachment to none and then back to fixed.还尝试将backgroundAttachment 重置为none,然后恢复为fixed。
I'm new to this so the code might be messy!我是新手,所以代码可能很乱!
Before I click the Button css for the background Image looks like this:在单击背景图像的按钮 css 之前,如下所示:
width: 100%;
height: 100%;
margin: 0;
background-image: url('../images/background-calculator.jpg');
background-position: center;
background-size: cover;
background-color: rgba(255, 255, 255, 0.486);
background-blend-mode: overlay;
background-attachment: fixed;
display: inline-block;
Afterwards I manipulated it via DOM in a javascript function:之后我在一个 javascript 函数中通过 DOM 操作它:
body.style.width = "100%";
body.style.height = "100%";
body.style.backgroundImage = "none";
body.style.backgroundImage = "url('../images/darkmode.jpg')";
body.style.backgroundPosition = "center";
body.style.backgroundSize = "cover";
body.style.backgroundColor = "transparent";
body.style.backgroundBlendMode = "none";
body.style.backgroundAttachment = "fixed";
body.style.display = "inline-block";
body.style.position = "relative";
Everything works except for the scrolling part.除了滚动部分,一切正常。
I think it can be solved by adding and removing class to the DOM.我认为可以通过在 DOM 中添加和删除类来解决。 Create two class corresponding to backgrounds.创建两个对应背景的类。
.dark-bg{background-image: url('../images/background-calculator.jpg');} .light-bg{background-image: url('../images/background-dark.jpg');} .dark-bg{background-image: url('../images/background-calculator.jpg');} .light-bg{background-image: url('../images/background-dark.jpg') ;}
Remove "dark-bg" when you apply light theme and vice-versa using JavaScript使用 JavaScript 应用浅色主题时删除“dark-bg”,反之亦然
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.