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

maz*_*aze 23 javascript jquery tooltip twitter-bootstrap

我正在使用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])'
});
Run Code Online (Sandbox Code Playgroud)

为了避免工具提示放置得太靠近屏幕边缘,我需要能够根据触发工具提示的元素的位置动态设置它们的位置.我想到了以下方式:

   $('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";
}
Run Code Online (Sandbox Code Playgroud)

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

提前致谢

dav*_*rad 34

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

this.options.placement.call(this, $tip[0], this.$element[0])
Run Code Online (Sandbox Code Playgroud)

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

$('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])'
});
Run Code Online (Sandbox Code Playgroud)


cha*_*tfl 5

placementdocs中的选项允许函数.它没有记录(我可以找到)函数中的参数.但是,通过登录arguments到控制台很容易确定.

这是你可以使用的:

$('body').tooltip({

   placement: function(tip, el){
     var position = $(el).position();
      /* code to return value*/

  }

/* other options*/
})
Run Code Online (Sandbox Code Playgroud)


sim*_*imo 5

这就是我在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);
}
Run Code Online (Sandbox Code Playgroud)

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

最后我添加了in显示工具提示的类.

另请注意,代码包含在setTimeout 0函数中.