问题
I've created a test case, please check it out as it illustrates my issue: http://jsfiddle.net/jAD2W/6/ (reduced example thanks to @patrick dw)
For completeness, this code has also been added to the bottom of this post.
Basically, whenever I get the offset of a span element or inline div element, the top
value is larger than it should be.
When you mouse-over the image in the example, it should stay at that absolute position. Unfortunately, it appears to be moved down.
What is causing it to move down? Removing the span element solves the problem, which indicates that it is caused by the inline property of the span element. Unfortunately, I do need the entire thing to be contained by a span or an inline div element.
The code from jsFiddle (html, javascript, css):
<html>
<body>
<div id='showArea'>
<span id="containerElement1">
<img src='http://twitpic.com/show/thumb/5lkmac.jpg' >
</span>
</div>
</body>
</html>
$('#containerElement1').mouseenter(function(e) {
var offset = $(this).offset();
$(this).css({
'position': 'absolute',
'top': offset.top,
'left': offset.left
});
});
img {
width:250px;
height:150px;
}
span {
width:250px;
height:150px;
}
回答1:
I think the problem is that as soon as you give the elements "position: absolute", you change a bunch of stuff about the layout. For starters, the <span>
elements are just "position: static" and "display: inline". Because they're inline, the "top" value looks big because they're set on a text baseline that's at the bottom of their container. The container <div>
is stretched around them, in other words, and the top is the top of the row of text (non-existent in your example, but that's what the browser thinks).
When you flip them to "position: absolute", the meaning of those things changes.
If you start things off with a CSS rule that gives the spans "display: inline-block", then the behavior changes (though it's still somewhat weird). (edit — ah, it's the "text-align: center" that's doing the horizontal movement. Once the first element is yanked out of the line, the other has to re-center itself.)
Note that when you add the spans, giving them a height has no effect; they're inline elements, not blocks.
edit — I've thought about how to do this, but it's a little tricky because it's not clear what effect you want. The problem is that the rules of layout for the inline content will affect the images and cause odd behavior. That "text-align: center", for example, will move things around as soon as you "pin" an image. Thus, with "inline-block", when you move over an element it will freeze in place, but the other image will then be adjusted to obey that "text-align" rule, and thus overlap the pinned one.
来源:https://stackoverflow.com/questions/6583586/jquery-offset-returns-invalid-value-for-span-or-inline-div