简体   繁体   中英

How to change element property with JS when it is set by CSS already?

My site's background-attachment is set to scroll in CSS :

body {background-attachment: scroll;}

I'm looking for a way to change it to fixed with JS depending on a condition . So far I've found two approaches which both do not seem to work:

1.

document.body.style.backgroundAttachment = "fixed";
window.getComputedStyle(document.body).backgroundAttachment = "fixed";

Approach 2 returns the right property:

alert(window.getComputedStyle(document.body).backgroundAttachment);

output:

scroll

but doesn't change it. Is this a cascading problem?

Your first setting:

document.body.style.backgroundAttachment = "fixed";

should work, in the sense that the value of that style should be changed to fixed. However, some browsers, most notably Safari, do not fully support fixed background attachments see https://caniuse.com/?search=background-attachment . I cannot tell from the code given in the question whether that is your problem here or not.

Your second setting:

window.getComputedStyle(document.body).backgroundAttachment = "fixed";

does not change the setting - as you can see from doing your alert immediately afterwards. Here's info from MDN:

The object from getComputedStyle is read-only, and should be used to inspect the element's style — including those set by a element or an external stylesheet.

Without more of your code which will show how you are testing for the condition I can't tell why method 1 won't work but method two certainly can't.

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