jquery position() not working correctly in safari and chrome

前端 未结 4 921
借酒劲吻你
借酒劲吻你 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.

提交回复
热议问题