我可以自定义此插件,以便单击文档中除选择框之外的任何其他位置时 - 它会关闭吗?我尝试为 body 标记添加点击事件,但似乎不起作用..
html
<select>
<option value="1">1</option>
<option value="2">2</option>
</select>
CSS
.selectbox {
width: 100px;
border: 1px solid #000;
padding: 2px 5px;
}
.list {
background-color: #eee;
border: 1px #ddd solid;
padding: 0;
position: absolute;
list-style: none;
width: 100%;
}
.list li:hover {
color: #fff;
background-color: #00f;
}
js
! function(t) {
return t.fn.selectbox = function(e) {
var i;
return i = t.extend({
customList: !1
}, e), this.each(function() {
var e, n, s, c;
return s = t(this).css({
opacity: 0,
position: "absolute",
"z-index": 2,
top: 0,
width: "100%",
height: "100%"
}), i.customList && (n = s.children()), c = s.wrap("<div class='selectbox'></div>").parent().css({
position: "relative"
}), c.append("<span class='value'>" + s.val() + "</span>"), i.customList && (s.hide(), e = c.append("<ul class='list'></ul>").find("ul"), n.each(function() {
return e.append("<li>" + this.text + "</li>")
}), e.hide()), s.on("change", function() {
return c.children(".value").text(t(this).val()), !1
}), i.customList && (c.click(function() {
return e.toggle(), !1
}), e.children().click(function() {
return e.toggle(), s.val(n.eq(e.children().index(this)).attr("value")).trigger("change"), !1
})), t(this)
})
}, !1
}(jQuery);
并使用此代码连接插件
$('select').selectbox({customList: true});
最佳答案
您可以像这样隐藏选项,绑定(bind)单击文档并检查选择框是否被单击,然后隐藏。
$(document).on('click',function(e){
if(!$(e.target).is('select')){
$('.selectbox ul').hide();
}
});
关于javascript - 自定义 jQuery 选择框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25997984/