jquery position() not working correctly in safari

2019-02-14 14:51发布

问题:

I've seen this question posed once or twice before, but never with an answer that applies to my problem (as far as I know). I have a tooltip that appears when a link is clicked. I set the position of the tooltip based on the position of the link similar to this:

$('#tooltip').css('left', $(this).position().left);

This works great in FF, IE, etc., but in Chrome and Safari, the tooltip is always about 60 pixels or so further to the left than I want. I really don't like writing browser specific code, so is there any reason anyone knows that this would be happening? Thanks in advance.

UPDATE: I was able to fix this problem by removing the margin:0 auto style from the link. Soooo...that fixed it, but I still have no idea WHY this was a problem in safari and chrome.

回答1:

position() relates to the position relative to the containing DOM element, as opposed to the position on screen. The difference is probably caused by differences in the way the element hierarchy is rendered in Webkit browsers, rather than by a bug in jQuery.

You will have to check element hierarchies to find out which DOM element is causing your problem, or, if you want to position your tooltip relative to the position of an element within the window boundaries, use offset() instead.



回答2:

Instead of using position() like in your example:

var link = $('#mymenu a');
var tooltip = $('#mymenu #tooltip');

link.click(function(){
  tooltip.css('left', $(this).position().left);
});

you can use subtraction of the element's offset() with offset() of it's parent (not necessarily the closest parent):

var parent = $('#mymenu');
var link = $('#mymenu a');
var tooltip = $('#mymenu #tooltip');

link.click(function(){
    parent.css('position', 'relative');
    tooltip.css('left', $(this).offset().left - parent.offset().left);
});

It returns the same value as position() but works correctly in both FF and Chrome.



回答3:

According to stackoverflow ettiquette, it's okay to answer you're own question, so... I was able to fix this problem by removing the margin:0 auto style from the link. Soooo...that fixed it, but I still have no idea WHY this was a problem in safari and chrome. But, still at least it's fixed.



回答4:

Just had the same problem, and removing margin: 0 auto; wasn't an option (nor is it a solution :). This worked for my needs, since webkit reports the value we're looking for as the left margin (so long as the margin is > 0, otherwise it does report position().left!):

iPosLeft = oEl.position().left + parseInt(oEl.css('marginLeft'));