firefox和Chrome的不同值

firefox和Chrome的不同值

本文介绍了jQuery $(' selector').css(' top')返回IE,firefox和Chrome的不同值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery $('selector').css('top')获得帮助定位动态元素的最高价值,我发现基于浏览器会得到不同的结果.

I am using the jQuery $('selector').css('top') to get the top value to help position dynamic elements and I find that I get different results based on the browser.

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

if the selector style is set to top:5%

Firefox返回5%.

Firefox returns 5%.

IE 7、8、9返回的像素值根据浏览器屏幕的宽度(哇)而变化.

IE 7, 8, 9 return a pixel value that changes depending on the WIDTH of the browser screen (wow).

Chrome返回自动".

Chrome returns 'auto'.

在以下测试html中,Firefox返回:

in the following test html,firefox returns:

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

IE 7、8、9返回:

IE 7, 8, 9 returns:

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

如果我加宽屏幕,则IE返回:

and if I widen the screen, IE returns:

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值,可能是auto1234px或类似名称-并不是获得最高排名的可靠方法.

Use $('selector').offset().top to get the numeric value of the top position.
.css() returns the CSS value of the top-position, which could be auto, 1234px, or something similar - not a reliable method to get the top position.

另请参阅:

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

这篇关于jQuery $(&amp;#39; selector&#39;).css(&amp;#39; top&amp;#39;)返回IE,firefox和Chrome的不同值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 06:31