[英]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.使用 JavaScript 我需要找到一个固定了 position 的元素并将其 top 属性设置为 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. element.style.prop
仅处理元素的inline
styles。 It is not affected by the changing of embedded
or external
styles (more information here ).它不受
embedded
或external
styles 更改的影响(此处有更多信息)。 Thus, you cannot use it to get the value of a non-inline
property.因此,您不能使用它来获取
non-inline
属性的值。
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
.从这里引用它们:
getComputedStyle
和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()
.您可以使用
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.它会返回一个 object 和所有styles,即使您没有明确定义,这与仅包含您明确设置的样式值的
style
属性不同。
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';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.