动态定位引导工具提示(用于动态生成的元素)



我正在使用Twitter Bootstrap(http://twitter.github.com/bootstrap/javascript.html#tooltips)提供的工具提示。

我的 DOM 中有一些动态插入的标记,需要触发工具提示。这就是我通过以下方式触发工具提示的原因 (https://github.com/twitter/bootstrap/issues/4215):

$('body').tooltip({
    delay: { show: 300, hide: 0 },
    selector: '[rel=tooltip]:not([disabled])'
});
为了避免工具提示

放置在离屏幕边缘太近的位置,我需要能够根据触发工具提示的元素的位置动态设置它们的位置。我想这样做的方式如下:

   $('body').tooltip({
        delay: { show: 300, hide: 0 },
        // here comes the problem...
        placement: positionTooltip(this),
        selector: '[rel=tooltip]:not([disabled])'
    });

function positionTooltip(currentElement) {
     var position = $(currentElement).position();
     if (position.left > 515) {
            return "left";
        }
        if (position.left < 515) {
            return "right";
        }
        if (position.top < 110){
            return "bottom";
        }
     return "top";
}

如何将 currentElement 正确传递给 positionTooltip 函数,以便为每个工具提示返回适当的放置值?

提前致谢

Bootstrap 使用包含元素的参数调用放置函数

this.options.placement.call(this, $tip[0], this.$element[0])

所以在你的情况下,这样做:

$('body').tooltip({
    delay: { show: 300, hide: 0 },
    placement: function(tip, element) { //$this is implicit
        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])'
});

这就是我在 Bootstrap 2.3.2 中放置工具提示的方式

placement: function (tooltip, trigger) {
    window.setTimeout(function () {
        $(tooltip)
            .addClass('top')
            .css({top: -24, left: 138.5})
            .find('.tooltip-arrow').css({left: '64%'});
        $(tooltip).addClass('in');
    }, 0);
}

基本上我在这里说的是,我的工具提示将位于顶部,带有一些自定义偏移量,底部的小三角形箭头也将略微偏右。

最后,我将添加显示工具提示的 in 类。

另请注意,代码包装在setTimeout 0函数中。

文档中的placement选项允许函数 .它没有记录(我可以找到)函数中有哪些参数。但是,通过将arguments登录到控制台很容易确定这一点。

以下是您可以使用的内容:

$('body').tooltip({
   placement: function(tip, el){
     var position = $(el).position();
      /* code to return value*/
  }
/* other options*/
})

这是我用来确定窗口宽度是否小于 768 的简写,然后从左到上更改工具提示位置:

placement: function(){return $(window).width()>768 ? "auto left":"auto top";}

这个对我有用

$("[rel=tooltip]").popover({
            placement: function(a, element) {
               var position = $(element).parent().position();
               console.log($(element).parent().parent().is('th:first-child'));
                if ($(element).parent().parent().is('th:last-child')) {
                    return "left";
                }
                if ($(element).parent().parent().is('th:first-child')) {
                    return "right";
                }
                return "bottom";
            },
        });

如果选项container设置为工具提示,$(element).position()将无法正常工作。

就我而言,我使用container : 'body',并且必须改用$(element).offset()

最新更新