jQuery偏移顶部无法正常工作 [英] jQuery offset top doesn't work correctly
问题描述
我正在尝试创建一个脚本,通过鼠标在元素中绘制一些东西,我使用 Raphaeljs
来做到这一点。
I'm trying to create an script draw something in an element by mouse and I'm using Raphaeljs
to do that.
为了正确绘图,我需要找到顶部
和左
输入
元素。我正在使用 var offset = $(#input)。offset();
获取左
和 top
。
For correct drawing I need to find top
and left
of input
element. I'm using var offset = $("#input").offset();
to get left
and top
.
但 top
值不正确。它的 10px
低于真正的顶部
距离。我认为 10px
可能会在不同的分辨率下改变,然后我不能正常添加 10px
然后我我想知道如何解决问题!
But the top
value isn't correct. It's 10px
lower than the real top
distance. I think the 10px
maybe change in different resolutions then I can't add 10px
to it normally then I want to know how can I fix the problem!
我上传了我的测试这里。
推荐答案
jQuery .offset()
函数有此限制:
The jQuery .offset()
function has this limitation:
注意:jQuery不支持获取隐藏元素的偏移坐标或计算body元素上的边框,边距或填充集。
Note: jQuery does not support getting the offset coordinates of hidden elements or accounting for borders, margins, or padding set on the body element.
在这种情况下,身体有一个10px的顶部边框,这就是你的绘图偏离了10个像素的原因。
The body in this case has a 10px top border, which is why your drawing is off by 10 pixels.
推荐的解决方案:
var offset = $("#input").offset();
x = x - offset.left - $(document.body).css( "border-left" );
y = y - offset.top + $(document.body).css( "border-top" );
这篇关于jQuery偏移顶部无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!