解决bootstrap的tooltip插件不能自动定位不是相对于浏览器窗口定位的问题

  • Post author:
  • Post category:其他


tooltip的插件参数:

选项名称 类型/默认值 Data 属性名称 描述
animation boolean


默认值:true
data-animation 向工具提示应用 CSS 褪色过渡效果。
html boolean


默认值:false
data-html 向工具提示插入 HTML。如果为 false,jQuery 的 text 方法将被用于向 dom 插入内容。如果您担心 XSS 攻击,请使用 text。
placement string|function


默认值:top
data-placement 规定如何定位工具提示(即 top|bottom|left|right|auto)。

当指定为

auto

时,会动态调整工具提示。例如,如果 placement 是 “auto left”,工具提示将会尽可能显示在左边,在情况不允许的情况下它才会显示在右边。
selector string


默认值:false
data-selector 如果提供了一个选择器,工具提示对象将被委派到指定的目标。
title string | function


默认值:”
data-title 如果未指定

title

属性,则 title 选项是默认的 title 值。
trigger string


默认值:’hover focus’
data-trigger 定义如何触发工具提示:

click| hover | focus | manual

。您可以传递多个触发器,每个触发器之间用空格分隔。
content string | function


默认值:”
data-content 如果未指定

data-content

属性,则使用默认的 content 值。
delay number | object


默认值:0
data-delay 延迟显示和隐藏工具提示的毫秒数 – 对 manual 手动触发类型不适用。如果提供的是一个数字,那么延迟将会应用于显示和隐藏。如果提供的是对象,结构如下所示:

delay:
{ show: 500, hide: 100 }:
{ show: 500, hide: 100 }
container string | false


默认值:false
data-container 向指定元素追加工具提示。

实例: container: ‘body’

按照tooltip的说明文档中可以看出,当我们调用这个插件并且给其传auto top会根据当前的位置自动确认显示方向。但是在计算时他的计算的是整个body元素的宽度和高度,而并不是相对于浏览器窗口自动定位。这样并不是那么的友好,在开发过程中找到的方法:

直接往参数palcement中传固定的显示方向,其具体的显示方向在调用时即计算好:

function

function confrimDirection(tip,element)
{




/*正则表达式*/
var autoToken = /\s?auto?\s?/i;
var autoPlace = autoToken.test(direction);
/*得到单个默认方向*/
if (autoPlace) {
   direction = direction.replace(autoToken, '') || 'top';
    $(tip).appendTo("body");

    /*计算tips的可视高度和宽度*/
    var $width = $(tip).width();
    var $height = $(tip).height();
    /*计算当前鼠标滑过的坐标*/
    var pos = $(element).offset();

    /*计算滚动条的高度*/
    var scroll = document.documentElement.scrollTop || document.body.scrollTop;

    /*计算当前对象距离可是窗口上边与右边的距离*/
    pos.bottom = $(window).height() - (pos.top - scroll) - $(element).height();
    pos.right = $(window).width() - pos.left - $(element).width();

    /* console.log("下边距为:"+pos.bottom+"右边距为:"+ pos.right);*/
    /*计算得到最合适的方向*/
    direction = direction == 'bottom' && pos.bottom < $height ? 'top' :
        direction == 'top' && (pos.top - scroll) < $height ? 'bottom' :
            direction == 'right' && pos.right < $width ? 'left' :
                direction == 'left' && pos.left < $width ? 'right' :
                    direction;
}
return direction;
}




在调用时直接:



jquery.tooltip({
    //加载插件,没有显示
   ………………//正常传参
    placement : confrimDirection//直接传函数即可
})



版权声明:本文为u012881878原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。