JQuery tooltip position

这一生的挚爱 提交于 2019-12-13 18:28:20

问题


I have been working on a simple tool tip (see fiddle below), but am having some positioning problems. I would like the tip to appear centered and above the link that is clicked. At the moment the top left corner is positioned at the mouse click. I tried to offset this position by half of the tooltip but to no success.

http://jsfiddle.net/Ricco/CBf4C/


回答1:


Check out the changes at http://jsfiddle.net/CBf4C/3/

You need to get the position of the clicked element (use .position()), get the dimensions of the tooltip with .outerWidth() and .outerHeight() and then calculate based on these..

the actual code is

$('a[title]').click(function(e) {

    //fadetooltip and display information
    $('body').append('<div class="tooltip"><div class="tipBody"></div></div>');
    tip = $(this).attr('title');
    var tooltip = $('.tooltip'); // store a reference to the tooltip to use it later
    tooltip.fadeTo(300, 0.9).children('.tipBody').html( tip );


    // calculate position of tooltip
    var el = $(this),
        pos = el.position(), // get position of clicked element
        w = el.outerWidth(), // get width of clicked element, to find its center
        newtop = pos.top - tooltip.outerHeight() , // calculate top position of tooltip
        newleft = pos.left + (w/2) - (tooltip.outerWidth()/2); // calculate left position of tooltip

    //set position
    $('.tooltip').css('left', newleft )  ;
    $('.tooltip').css('top',  newtop );

    hideTip = false;
});



回答2:


http://jsfiddle.net/CBf4C/15/ - see this.




回答3:


See the changes I've made here: http://jsfiddle.net/CBf4C/9/



来源:https://stackoverflow.com/questions/12491197/jquery-tooltip-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!