2017-01-16 76 views
0

我有一個JavaScript文件最後加載。在該文件的代碼被執行:未捕獲TypeError不能設置未定義的屬性'top'

var x = document.getElementById("bildfram1").offsetHeight; 

document.getElementsByTagName("header").style.top = "calc(x/2)"; 

但我在控制檯收到此錯誤:

Uncaught TypeError: Cannot set property 'top' of undefined

關於如何解決此問題的任何幫助! 在此先感謝!

+2

的[JavaScript中的潛在重複| Uncaught TypeError:無法設置屬性的'顏色'未定義](http://stackoverflow.com/questions/30232423/javascript-uncaught-typeerror-cannot-set-property-color-of-undefined) –

+1

可能重複[什麼querySelectorAll,getElementsByClassName和其他getElementsBy \ *方法返回?](http://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method) – Xufox

回答

0

getElementsByTagName返回元素的HTMLCollection(陣列狀物體)。

因此,您需要定位特定索引(es)。

document.getElementsByTagName('header')[0].style.top = "calc(x/2)"

calc是一個實驗性的技術。如果你只需要做一個簡單的分配,你應該事先做好。

var division = val/2; 
document.getElementByTagName('header')[0].style.top = divison + 'px' 
相關問題