Reputation: 5751
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?
Upvotes: 0
Views: 86
Reputation: 36426
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.
Upvotes: 3