更新时间:2023-10-30 19:22:52
在 http://上查看更改jsfiddle.net/CBf4C/3/
您需要获取被单击元素的位置(使用 .position()
),请使用 .outerWidth()
和
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..
实际代码是
$('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;
});