简体   繁体   中英

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.

I'm new to this so the code might be messy!

Before I click the Button css for the background Image looks like this:

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:

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. Create two class corresponding to backgrounds.

.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM