简体   繁体   中英

How can I use JavaScript to find if an element has position fixed?

Using JavaScript I need to find an element that has position fixed and set its top attribute to 60px.

const myDiv = document.querySelector('.my-div')
if(myDiv && myDiv.style.position == 'fixed') {
    myDiv.style.top = '60px';
}

But it doesn't work. What is wrong in my code?

The element.style.prop deals with the inline styles of an element, only. It is not affected by the changing of embedded or external styles (more information here ). Thus, you cannot use it to get the value of a non-inline property.

Therefore, you need to use this:-

const myDiv = document.querySelector('.my-div');

if (myDiv && window.getComputedStyle(myDiv).getPropertyValue('position') == 'fixed') {
    myDiv.style.top = '60px';
}

Refer them from here: getComputedStyle and getPropertyValue .

Or even more simply, you could simply use the . or the [] notation to get the values. You can check out the differences here .

const myDiv = document.querySelector('.my-div');

if (myDiv && window.getComputedStyle(myDiv).position == 'fixed') {
    myDiv.style.top = '60px';
}

You can use window.getComputedStyle() .

It will return an object with all styles, even if not explicitly defined by you, unlike the style property which only holds the style values which you explicitly set.

For your code, it would look like this:

const myDiv = document.querySelector('.my-div')
if (!myDiv) return; // Early return guard to avoid calling getComputedStyle with null
const style = window.getComputedStyle(myDiv)

if (style.position === 'fixed') {
    myDiv.style.top = '60px';
}

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