Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

javascript - jQuery offset top doesn't work correctly

I'm trying to create an script draw something in an element by mouse and I'm using Raphaeljs to do that.

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.

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!

I uploaded my test here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The jQuery .offset() function has this limitation:

Note: jQuery does not support getting the offset coordinates of hidden elements or accounting for borders, margins, or padding set on the body element.

The body in this case has a 10px top border, which is why your drawing is off by 10 pixels.

Recommended solution:

var offset = $("#input").offset();
x = x - offset.left - $(document.body).css( "border-left" );
y = y - offset.top + $(document.body).css( "border-top" );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...