我使用 jQuery $('selector').css('top') 获取顶部值来帮助定位动态元素,我发现根据浏览器得到不同的结果。
如果选择器样式设置为top:5%
Firefox 返回 5%。
IE 7、8、9 返回一个像素值,该值根据浏览器屏幕的宽度而变化(哇)。
Chrome 返回“自动”。
在下面的测试 html 中, 火狐返回:
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( )
返回顶部位置的 CSS 值,可能是 auto
、1234px
或类似的值 - 这不是获取顶部位置的可靠方法。
另请参阅:
关于jquery $ ('selector' ).css ('top' ) 为 IE、firefox 和 Chrome 返回不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7891824/