jquery $('selector')。css('top')为IE,firefox和Chrome返回不同​​的值 [英] jquery $('selector').css('top') returns different values for IE, firefox and Chrome

查看:152
本文介绍了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返回根据浏览器屏幕(WOW)的WIDTH而变化的像素值。

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

Chrome返回auto。

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>


推荐答案

使用 $ ').offset()。top 获取顶部位置的数值。
.css ()返回顶部位置的CSS值,可以 auto 1234px

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 $('selector')。css('top')为IE,firefox和Chrome返回不同​​的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆