Javascript – element.style.left returning blank

when I try to check what the value of left is using javascript, it shows to be "". The following JS is used to check the value:

var menuElement = document.getElementById('menu');
console.log(menuElement.style.left);

You have to use getComputedStyle() to get the rules declared via stylesheet.

var menuElement = document.getElementById('menu');
console.log(getComputedStyle(menuElement).left);
console.log(getComputedStyle(menuElement));

結論: 無效, 但直接使用jQuery 的 attr 屬性, assisn 進 element 的 style 裡, 是可以的, 例如:

div.attr("style","left:100px;top:100px;");

如果是使用javascript 可以使用 Element.setAttribute()

Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.

To get the current value of an attribute, use getAttribute(); to remove an attribute, call removeAttribute().

setAttribute(name, value)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *