您可以使用鼠标位置作为工具提示锚点,也可以修改工具提示 JavaScript 代码以实现此目的,如 How to make popover appear where my mouse enters the hover target? 中所示。您可以将底部代码与链接中的代码合并以实现两者并选择您喜欢的代码。
在 bootstrap-tooltip.js 中,替换(我认为是第 1602 行)(抱歉格式不佳)
Tooltip.prototype.getPosition
and
Tooltip.prototype.getCalculatedOffset
函数分别
Tooltip.prototype.getPosition = function($element) {
$element = $element || this.$element
var el = $element[0]
var isBody = el.tagName == 'BODY'
var elRect = el.getBoundingClientRect()
if (elRect.width == null) {
// width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
elRect = $.extend({}, elRect, {
width: elRect.right - elRect.left,
height: elRect.bottom - elRect.top
})
}
var rects = el.getClientRects();
var firstRect = rects[0];
var lastRect = rects[rects.length - 1];
firstRect = $.extend({}, firstRect, {
width: firstRect.right - firstRect.left,
height: firstRect.bottom - firstRect.top
})
lastRect = $.extend({}, lastRect, {
width: lastRect.right - lastRect.left,
height: lastRect.bottom - lastRect.top
})
var elOffset = isBody ? {
top: 0,
left: 0
} : $element.offset()
var elScrollTop = elOffset.top - elRect.top;
var elScrollLeft = elOffset.left - elRect.left;
firstRect.top += elScrollTop;
lastRect.top += elScrollTop;
firstRect.left += elScrollLeft;
lastRect.left += elScrollLeft;
firstRect = {
firstRect: firstRect
};
lastRect = {
lastRect: lastRect
};
var scroll = {
scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop()
}
var outerDims = isBody ? {
width: $(window).width(),
height: $(window).height()
} : null
return $.extend({}, elRect, scroll, outerDims, elOffset, firstRect, lastRect)
}
Tooltip.prototype.getCalculatedOffset = function(placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? {
top: pos.top + pos.height,
left: pos.left + pos.width / 2 - actualWidth / 2
} :
placement == 'top' ? {
top: pos.top - actualHeight,
left: pos.left + pos.width / 2 - actualWidth / 2
} :
placement == 'left' ? {
top: pos.top + pos.height / 2 - actualHeight / 2,
left: pos.left - actualWidth
} :
placement == 'textleft' ? {
top: pos.firstRect.top + (pos.firstRect.height / 2) - actualHeight / 2,
left: pos.firstRect.left - actualWidth
} :
placement == 'textright' ? {
top: pos.lastRect.top + (pos.lastRect.height / 2) - actualHeight / 2,
left: pos.lastRect.right
} :
/* placement == 'right' */
{
top: pos.top + pos.height / 2 - actualHeight / 2,
left: pos.left + pos.width
}
}
现在您可以使用展示位置“textleft”和“textright”。
这适用于 Bootstrap v3.3.6。可以通过不直接编辑引导源而是对其进行扩展来改进它(而且有点脏)。
您还需要将此添加到 css 中以获得工具提示箭头。
.tooltip.textright {
padding: 0 5px;
margin-left: 3px;
}
.tooltip.textleft {
padding: 0 5px;
margin-left: -3px;
}
.tooltip.textleft .tooltip-arrow{
top: 50%;
right: 0;
margin-top: -5px;
border-width: 5px 0 5px 5px;
border-left-color: #000;
}
.tooltip.textright .tooltip-arrow{
top: 50%;
left: 0;
margin-top: -5px;
border-width: 5px 5px 5px 0;
border-right-color: #000;
}
这里是小提琴:JSFiddle