所以我試圖創建一個可搜索的div列表,用戶可以用它來快速跳轉到頁面上的位置。這是使用Flask和Bootstrap。Searchable Bootstrap Dropdown
我成功構建了一個下拉菜單來執行此操作,但它無法搜索。
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
Quick Scroll
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
{% for company in active_companies %}
<a class="dropdown-item" href="#company_{{ company[0] }}"
role="button">
{{ company[1] }}
</a>
{% endfor %}
</div>
</li>
我試過Bootstrap-Select,但我似乎無法得到正確加載庫。也許是Bootstrap 4問題,也許是Flask,也許是我。我嘗試加載Semantic UI's dropdown module(並重構以避免任何衝突),但那也不起作用。所以我決定把我自己放在一起。
我現在有這樣的事情。單擊輸入框後可以看到下拉菜單,並在點擊輸入框時關閉。 如果我可以在其他地方點擊關閉它,我會滿意。但我嘗試使用window.onclick失敗。
如果你能指向一個可行的Bootstrap實現,或者看到我在做什麼(我確信有無數的缺陷)的漏洞,請告訴我。
<form class="form-inline my-2 my-lg-0">
<input onclick="myFunction()" type="text" class="live-search-box" placeholder="Company/Complex"/>
<ul class="live-search-list dropdown-menu scrollable-menu" id="toggle-thingy">
{% for company in active_companies %}
<li>
<a class="dropdown-item" href="#company_{{ company[0] }}">
{{ company[1] }}
</a>
</li>
{% endfor %}
{% for complex in company_complex %}
<li>
<a class="dropdown-item" href="#P{{ complex[2] }}">
{{ complex[3] }}
</a>
</li>
{% endfor %}
</ul>
</form>
使用此JS:
jQuery(document).ready(function($){
/* Searches List Items */
$('.live-search-list li').each(function(){
$(this).attr('data-search-term', $(this).text().toLowerCase());
});
$('.live-search-box').on('keyup', function(){
var searchTerm = $(this).val().toLowerCase();
$('.live-search-list li').each(function(){
if ($(this).filter('[data-search-term *= ' + searchTerm + ']').length > 0 || searchTerm.length < 1) {
$(this).show();
} else {
$(this).hide();
}
});
});
});
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("toggle-thingy").classList.toggle("show");
}
而這個CSS:
.live-search-list {
position: absolute;
margin-left: 10px;
margin-right: 10px;
top: 100%;
left: 0;
z-index: 1000;
/*display: inline-block;*/
float: left;
min-width: 10rem;
padding: 0 0;
font-size: 0.875rem;
color: #263238;
text-align: left;
list-style: none;
background-color: #fff;
background-clip: padding-box;
border: 1px solid #cfd8dc;
}
.live-search-box {
padding: 0.5rem 0.75rem;
font-size: 0.875rem;
line-height: 1.25;
color: #607d8b;
background-color: #fff;
background-image: none;
background-clip: padding-box;
border: 1px solid rgba(0, 0, 0, 0.15);
border-radius: 0;
transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
}
.live-search-list li {
list-style: none;
padding: 0;
margin: 5px 0;
}
.show {display:inline-block;}
.scrollable-menu {
height: auto;
max-height: 200px;
overflow-x: hidden;
}
你試過'select2'嗎? –
不,我會給它一個 – Jon