jQuery工具提示位置 [英] JQuery tooltip position
问题描述
我一直在研究一个简单的工具提示(请参见下面的小提琴),但是遇到一些定位问题.我希望提示显示在所单击链接的上方和上方.此刻,单击鼠标左上角即可.我试图用工具提示的一半来抵消这个位置,但是没有成功.
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/
推荐答案
在 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;
});
这篇关于jQuery工具提示位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!