jquery $('selector').css('top') 为 IE、Firefox 和 Chrome 返回不同的值



我使用jQuery $('selector').css('top')来获取顶值,以帮助定位动态元素,我发现我得到不同的结果基于浏览器。

如果选择器样式设置为top:5%

Firefox返回5%。

ie7, 8, 9返回一个像素值,该值根据浏览器屏幕的宽度(wow)而变化。

Chrome返回'auto'.

在下面的测试html中,firefox的回报:

m1 - 5%
m2 - 100%
m3 - 100px

IE 7, 8, 9返回:

m1 - 25px
m2 - 509px
m3 - 100px

,如果我扩大屏幕,IE返回:

m1 - 49px
m2 - 977px
m3 - 100px
Chrome的回报:

m1 - auto
m2 - auto
m3 - auto

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<style type="text/css">
#m1 {top:5%;}
#m2 {top:100%;}
#m3 {top:100px;}
</style>
<title>CSS Test</title>
</head>
<body>
<div class="m" id='m1'>m1</div>
<div class="m" id='m2'>m2</div>
<div class="m" id='m3'>m3</div>
<script type="text/javascript">
function get_css() {
    var output = "";
    $('.m').each(function(){
        output +=  $(this).html() + ' - ' +$(this).css('top')+ "<br />";
    });
    $('#output').html(output);
}
</script>
<br /><input type='button' name='get_css' value="css('top')" onclick="get_css()"/>
<p><div id='output'></div></p>
</body>
</html>

使用$('selector').offset().top获取top位置的数值。
.css()返回top-position的CSS值,可以是auto1234px或类似的值——这不是获得top position的可靠方法

参见:

  • http://api.jquery.com/offset/
  • http://api.jquery.com/position/

问题是,您的测试元素实际上都没有动态定位。参见这个问题:jQuery .css("left")返回"auto"而不是实际值

最新更新