这是我的 previous question 的跟进.
我需要动态放置 Bootstrap 工具提示。为此,我需要知道触发工具提示的元素的位置(工作正常)以及应该显示的工具提示的宽度:
编辑澄清: 我的工具提示是动态生成的,然后插入到内容中。例如,如果它们离屏幕的左边缘太近,我需要将它们放在“右”而不是“上”。现在我想让工具提示的宽度仅在它实际离开屏幕时才将其放在“正确”位置。
$('body').tooltip({
delay: { show: 300, hide: 0 },
selector: '[rel=tooltip]:not([disabled])',
placement: function(tip, element) {
var offsetLeft = $(element).offset().left;
var offsetRight = ( $(window).width() - ( offsetLeft + $(element).outerWidth() ) );
// need help here: how to get the width of the current tooltip?
// currently returns "0" for all elements
var tooltipWidth = $(tip).outerWidth();
console.log(tooltipWidth);
if (offsetLeft < 220) {
return 'right';
}
if (offsetRight < 220) {
return 'left';
}
else {
return 'top';
}
}
});
提前致谢。
最佳答案
从逻辑的 Angular 来看,这是不可能的 :) 想一想 - 工具提示调用放置函数来获取其位置,然后它将提示插入页面并为其设置样式。
但是,您可以创建一个与即将到来的尖端具有相同特征的虚拟尖端,并由此获得宽度。像这样:
$('body').tooltip({
delay: { show: 300, hide: 0 },
placement: function(a, element) {
//title is by tooltip moved to data-original-title
var title=$(element).attr('data-original-title');
//create dummy, a div with the same features as the tooltïp
var dummy=$('<div class="tooltip">'+title+'</div>').appendTo('body');
var width=$(dummy).width();
dummy.remove();
//now you have width
//..
//..
var position = $(element).position();
if (position.left > 515) {
return "left";
}
if (position.left < 515) {
return "right";
}
if (position.top < 110){
return "bottom";
}
return "top";
},
selector: '[rel=tooltip]:not([disabled])'
});
关于javascript - 获取工具提示的宽度并计算位置(Twitter Bootstrap),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13526653/