2017-04-27 61 views
3

我想在禁用的按鈕上使用Bootstrap工具提示,讓用戶知道爲什麼按鈕處於這種狀態。但是,大多數瀏覽器不會在禁用的元素上觸發點擊或懸停事件,這使事情變得更加困難。禁用按鈕解決方法的自舉工具提示

我試圖在div中包裝按鈕並初始化此元素中的工具提示,正如我在SO周圍找到的this解決方案所建議的那樣。

所以我想這樣的:

<div id="disabled-button-wrapper" data-title="Tooltip title"> 
    <button class="btn btn-primary" disabled="disabled">Button</button> 
</div> 

<script> 
    $(function() { 
     $('#disabled-button-wrapper').tooltip(); 
    }); 
</script> 

jsfiddle

但提示是不工作的。實際上,它甚至不是因爲按鈕,無論內容是什麼,工具提示都不適用於包裝div。這裏發生了什麼?我錯過了什麼明顯的細節?

編輯:與Chrome瀏覽器開發工具檢查當我真的看到正在生成工具提示元素,但也有幾個問題:

  • 盤旋權當它是唯一的觸發按鈕:div取所有的寬度(順便說一句,我希望父級和按鈕一樣寬)。但是,當鼠標懸停在按鈕上方時並非如此。
  • 工具提示元素隱藏在某處,無法正確呈現。

編輯2:我做了一些改變:jsfiddle

這樣的包裝並不需要所有的寬度,並使用人體作爲容器將解決渲染問題。現在剩下的唯一問題是:爲什麼懸停在禁用按鈕的部件上時,包裝器上不會觸發懸停事件?

+0

好了,的jsfiddle不起作用,因爲你還沒有加載必要的庫... – junkfoodjunkie

+0

@junkfoodjunkie是的,我有嗎? – dabadaba

+0

我的不好,它沒有顯示外部資源。 – junkfoodjunkie

回答

2

如果你真的真的檢查jsfiddle 你可以看到一些CSS在那裏

  1. 增加一定的餘量,所以我們可以看到提示,默認的按鈕上方

2.css,不讓按鈕阻止鼠標事件到達包裝

#disabled-button-wrapper { 
    display: inline-block; /* display: block works as well */ 
    margin: 50px; /* make some space so the tooltip is visible */ 
} 

#disabled-button-wrapper .btn[disabled] { 
    /* don't let button block mouse events from reaching wrapper */ 
    pointer-events: none; 
} 

dem ○:https://jsfiddle.net/dLt2ed5w/6/

+0

也在'#下添加'cursor:not-allowed;''禁用按鈕包裝「,使它看起來像一個禁用的按鈕 –

1

How to enable bootstrap tooltip on disabled button?

$(function() { 
 
    $('[data-toggle="tooltip"]').tooltip(); 
 
});
#disabled-button-wrapper { 
 
    display: inline-block; 
 
} 
 

 
#disabled-button-wrapper .btn[disabled] { 
 
    pointer-events: none; 
 
} 
 

 
#disabled-button-wrapper { 
 
    cursor: not-allowed; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> 
 
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> 
 

 
<div id="disabled-button-wrapper" data-placement="right" data-toggle="tooltip" data-title="Tooltip title"> 
 
    <button class="btn btn-primary" disabled>Button</button> 
 
</div>

1

你需要以下CSS。

#disabled-button-wrapper .btn[disabled] { 
    /* you need this line, not to block hover event from div */ 
    pointer-events: none; 
} 
#disabled-button-wrapper { 
    display: inline-block; /* display: block works as well */ 
    margin: 50px; /* make some space so the tooltip is visible */ 
} 

說明: -

您需要設置pointer-events: none;殘疾人按鈕,怎麼一回事,因爲禁用按鈕實際上阻止其父容器的事件,所以你需要告訴不要擋住懸停事件從容器正在添加。

Demo