Firefox和Chrome为offsetTop赋予不同的值 [英] Firefox and Chrome give different values for offsetTop

查看:119
本文介绍了Firefox和Chrome为offsetTop赋予不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试相对于输入字段定位一个span元素(我们称其为工具提示范围)。为此,我将工具提示跨度和输入字段包装在另一个具有位置:相对的跨度元素(我们称之为包装器跨度)中。然后在工具提示跨度上设置 position:absolute 。这样可以使工具提示跨度位置本身相对于包装跨度,但不属于页面流-不占用任何空间。正是我想要的。

I am trying to position an span element (let us call it "the tooltip span") relative to a input field. To do this, I am wrapping the tooltip span and the input field in another span element (let's call it "the wrapper span") that has position: relative. Then I set position: absolute on tooltip span. This makes the tooltip span position itself relative to the wrapper span but not being part of the page flow - not taking up any space. This is exactly what I want.

然后,使用javascript,我将工具提示的位置设置为相对于input元素的位置。由于输入元素在不同页面上的形状可能不同(脚本应适用于世界),我使用的是 offsetTop offsetLeft 属性以计算其相对于包装范围的位置。

Then, using javascript, I set the position of the tooltip relative to the position of the input element. Since the input element can be shaped differently on different pages (script should be globablly applicable), I am using its offsetTop and offsetLeft properties to calculate its position relative to the wrapper span.

但是,我注意到此处的浏览器之间存在不一致之处。在Firefox,IE6、7、8中,它可以正常工作。但是在Chrome和Safari中,报告的 offsetTop 似乎很好,这是不正确的。

However, I am noticing inconsistencies between browsers here. In Firefox, IE6, 7, 8, it works as expected. But in Chrome and Safari the reported offsetTop seems, well, incorrect.

为了证明这一点,我创建了测试以下页面:

To prove this, I created the test page below:

<html>
<head>
<style type="text/css">
span { font-size: 8px; position: relative; top: 0; left: 0; border: 1px solid red } 
</style>
</head>
<body>

<span id="wrapper">
<input id="foo" name="foo" type="text">
</span>

<script type="text/javascript">
document.write("<br>Offset parent: " + document.getElementById("foo").offsetParent.id);
document.write("<br>Offset top: " + document.getElementById("foo").offsetTop);
</script>

</body>
</html>

并将其加载到Firefox和Chrome中。两种浏览器都将包装器范围报告为 offsetParent ,但是对于Firefox, offsetTop 为-8,对于Chrome,为2

and loaded it in Firefox and Chrome. Both browser report the wrapper span as its offsetParent, but for Firefox the offsetTop is -8 and for Chrome it is 2. Visually the page renders the same in both browsers.

这让我很头疼,因为我不能仅仅破解别人在使用Chrome时总是应用的偏移量。 ,因为如果更改字体大小, offsetTop 不会更改,并且脚本会中断。

This gives me a headache, because I cannot just hack in a different offset that I always apply when someone is using Chrome, because if I change the font size, the offsetTop will not change, and my script will break.

是这是一个错误吗?我可以解决这个问题吗?

Is this a bug? Can I solve this differently?

推荐答案

使用jQuery。浏览器之间的DOM差异是它擅长的事情之一。

Use jQuery. DOM differences between browsers is one of the things it excels at.

这篇关于Firefox和Chrome为offsetTop赋予不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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