jquery position() not working correctly in safari and chrome

前端 未结 4 917
借酒劲吻你
借酒劲吻你 2021-01-06 03:54

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 cli

相关标签:
4条回答
  • 2021-01-06 04:32

    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.

    0 讨论(0)
  • 2021-01-06 04:37

    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'));
    
    0 讨论(0)
  • 2021-01-06 04:44

    According to stackoverflow ettiquette, it's okay to answer your 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.

    0 讨论(0)
  • 2021-01-06 04:46

    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.

    0 讨论(0)
提交回复
热议问题