谁能告诉我这个JS片段的问题是什么?我试图将'容器的margin-top的值赋给m变量。
function test()
{
var e = document.getElementById('container');
var m = e.style.getPropertyValue("marginTop");
alert (m);
}
编辑:警报旨在显示m
的值答案 0 :(得分:0)
试试这个:
function getStyle(elment, style) {
var x = document.getElementById(element);
if (x.currentStyle) {
var y = x.currentStyle[style];
} else if (window.getComputedStyle) {
var y = document.defaultView.getComputedStyle(x, null).getPropertyValue(style);
}
return y;
}
function test() {
var m = getStyle('container', 'margin-top');
alert(m);
}
另外,请注意您的变量范围。不会在m
之外定义test()
。
答案 1 :(得分:0)
您可以尝试使用这个简单的功能:
function test()
{
var e = document.getElementById('container');
var m = getStyle(e, "marginTop");
alert ('hi ' + m);
}
function getStyle(el,styleProp)
{
if (el.currentStyle)
var y = el.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
else
var y = el.style[styleProp];
return y;
}