[英]Javascript:How can I find the position of element in the multi-dimensional array
[英]How can I use JavaScript to find if an element has position fixed?
使用 JavaScript 我需要找到一個固定了 position 的元素並將其 top 屬性設置為 60px。
const myDiv = document.querySelector('.my-div')
if(myDiv && myDiv.style.position == 'fixed') {
myDiv.style.top = '60px';
}
但它不起作用。 我的代碼有什么問題?
element.style.prop
僅處理元素的inline
styles。 它不受embedded
或external
styles 更改的影響(此處有更多信息)。 因此,您不能使用它來獲取non-inline
屬性的值。
因此,你需要使用這個:-
const myDiv = document.querySelector('.my-div');
if (myDiv && window.getComputedStyle(myDiv).getPropertyValue('position') == 'fixed') {
myDiv.style.top = '60px';
}
從這里引用它們: getComputedStyle
和getPropertyValue
。
或者更簡單地說,您可以簡單地使用.
或[]
表示法來獲取值。 您可以在此處查看差異。
const myDiv = document.querySelector('.my-div');
if (myDiv && window.getComputedStyle(myDiv).position == 'fixed') {
myDiv.style.top = '60px';
}
您可以使用window.getComputedStyle()
。
它會返回一個 object 和所有styles,即使您沒有明確定義,這與僅包含您明確設置的樣式值的style
屬性不同。
對於您的代碼,它看起來像這樣:
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.