如何使用JavaScript检测动态变化的边距的大小?

时间:2015-12-13 15:17:10

标签: javascript jquery margin

在我的html中,我有一个div,div有一个随机的左边距:
HTML:

<div id=box1></div>

JAVASCRPIT:

$('#box1').css({'margin-left':Math.floor((Math.random()*450)+0)});

问题在于每当我试图检查保证金的大小时,就像这样:

document.write($('#box1').css('margin-left'));

即使边距不同,它也始终显示0px。 如果我尝试用'if'语句检查,我会遇到同样的问题。

2 个答案:

答案 0 :(得分:0)

您只需更改document.write

即可
$('#box1').css({'margin-left':Math.floor((Math.random()*450)+0)});
alert($('#box1').css('margin-left'));

Demo

答案 1 :(得分:0)

谢谢你们的帮助,我设法让它发挥作用。问题是我的document.write试图过早地获得价值。如果我添加这样的延迟,它可以工作:

setTimeout(show,500); 
function show() {
    document.write($('#box1').css('margin-left'));
};