最近碰到一個需求 要求點擊時浮現氣泡框來展示文本內容 理想中的效果如下
網上搜了下 看到bootstrap有現成popover 插件用來實現這個的 ,現成的輪子不用白不用 引入bootstrap 的css和js 就可以開始了
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
引入頭文件後,在需要點擊的地方寫上一些內置的屬性,筆者這裏因爲業務要求 所以用的是a標籤
<a type="button" title="" data-container="body" data-toggle="popover" data-placement="left" data-content="氣泡的內容" }">查看詳情</a>
簡單說下 一些屬性,title的內容會伴隨內容一起浮現標題,一般是缺省的, data-container="body" data-toggle="popover" 爲固定寫法, data-placement="left" 爲向左方向展示氣泡彈框,可以根據自己需求 改爲 bottom 、top、right等不同的方向,data-content="氣泡的內容" 就是點擊標籤後 氣泡彈框浮現的文字內容。
接下來就是初始化需要在script標籤內加上,不然點擊是不會出現效果的。
$(function () {
$("[data-toggle='popover']").popover();
});
現在不出意外的話 點擊a標籤就已經能夠浮現內容了,但是還有個小問題,點擊a標籤浮現的氣泡框,需要再次點擊氣泡框纔會消失,這樣比較麻煩,不太符合實際需求,所以需要再加上點擊父元素 body時 讓已經出現的氣泡框隱藏起來,因此再次在上面的基礎上添加js代碼來解決這種情況
$(function () {
$("[data-toggle='popover']").popover();
$('body').on('click', function (e) {
$('[data-toggle="popover"]').each(function () {
if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
$(this).popover('hide');
}
});
});
$('body').on('hidden.bs.popover', function (e) {
$(e.target).data("bs.popover").inState.click = false;
});
});
到這一步 就大功告成了,感興趣的可以去試一試。
附上最終實現截圖:
官方參考用例:
https://www.runoob.com/try/try.php?filename=bootstrap3-plugin-popover