[英]jquery $('selector').css('top') returns different values for IE, firefox and Chrome
我正在使用jQuery $('selector')。css('top')來獲取最高值,以幫助定位動態元素,並且我發現基於瀏覽器會得到不同的結果。
如果選擇器樣式設置為top:5%
Firefox返回5%。
IE 7、8、9返回的像素值根據瀏覽器屏幕的寬度而變化(哇)。
Chrome返回“自動”。
在以下測試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()
返回頂部位置的CSS值,該值可以是auto
, 1234px
或類似名稱-不是獲取頂部位置的可靠方法。
也可以看看:
問題是,您的所有測試元素實際上都沒有動態定位。 看到這個問題: jQuery .css(“ left”)在Chrome中返回“ auto”而不是實際值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.