我知道这篇文章已经过时了。但是,我有一个不同的解决方案,它对我很有效,我想分享一下。
我在 @John Knott 的解决方案的基础上使用 mdl 文本字段与 select as mdl-textfield__input + @user2255242 的菜单解决方案,但不涉及 js。
这是一个说明解决方案的小提琴。
JS fiddle for MDL select box
HTML - 我使用了一个文本字段 + 一个菜单 (ul + li) 作为选择,其余的由 css 完成。
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<div id="app">
<div class="sorter-holder">
<!-- the textfield, notice the readonly on input -->
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text" v-model="sortBy" id="sorterHolder" readonly>
<label class="mdl-textfield__label" for="sorterHolder">Sort by</label>
</div>
<!-- menu which will act as the options of select. The menu is for the input, and not the div which has mdl-textfield class -->
<ul class="mdl-menu mdl-menu--bottom-left mdl-js-menu mdl-js-ripple-effect sorter-menu" for="sorterHolder">
<li class="mdl-menu__item" v-for="srtr in sortables" @click="update(srtr)">{{ srtr }}</li>
</ul>
</div>
</div>
CSS - 主要部分是 css
/*
The menu is positioned absolute, and it's positions are calculated dynamically (I think). I wanted it to extend for the entire width of input, and for that needed a relative parent.
Also, the display inline-block was not required in where I actually implemented it. Over there, it was block. So, this might need to change according to layout. */
.sorter-holder {
position: relative;
display: inline-block;
}
/* just giving them a width of 100% to extend for the entire textfield */
.sorter-holder .mdl-menu__outline,
.sorter-holder .mdl-menu__container,
.sorter-menu {
width: 100% !important;
}
VueJS - 这个例子是在 Vue JS 中,但可以很容易地在任何其他框架中复制,因为主要是由 HTML + CSS 执行的
new Vue({
el: "#app",
data: {
sortables: [
'Name (A-Z)',
'Name (Z-A)',
'Newest First',
'Oldest First'
],
sortBy: null
},
methods: {
update: function (sortBy) {
this.sortBy = sortBy;
}
}
})
为什么我会这样做?
菜单看起来比默认浏览器的选择框更好。但是,不想对选择的选项做一些 CSS 魔术。而且,这似乎比那更容易。
这可以通过很多其他方式来完成。我发现它更好,并在我的一个项目中实施。希望能帮助到你! :)