javascript - 单击选择时停止 chrome 显示下拉列表

标签 javascript google-chrome

我想点击一个<select>但停止它以显示他的下拉列表

$('select').click(function(){
    if ($(this).find('option').size() > 20) {
        // some code to do my job
        return false;
    }
});

代码return false在 Firefox 中可以停止显示下拉列表(实际上是下拉列表先显示然后隐藏),但在 Chrome 中不起作用。

我也试过让 <select>要禁用,触发 blur()在上面,或者触发 click()在其他元素上,但下拉列表仍然存在,除非用户单击其他地方。

这可能吗? ...谢谢!


长话短说(如果你对我为什么要这么做感兴趣的话):

As you know, sometimes there will be a <select> with too many <option> in it, and when you click it, there will be a long dropdown list. Find what you need in a long dropdown list is a terrible job... But unfortunately there is a lot in my site.

So I think the simplest way is to write some javascript to change that, when option is more than 20, show a dialog with a filter and a new <select> which only have filtered <option> to let find easy.

And my problem is the dropdown list is still display, make my users confused... They don't know where to operate. "the dialog or the origin select".

最佳答案

问题是 select 元素的默认操作发生在 mousedown 事件上,而不是 click(或 mouseup ),因此您需要将事件处理程序绑定(bind)到 mousedown:

$("select").mousedown(function(e) {
    if ($(this).find('option').length > 20) {
        e.preventDefault(); //return false will also work
    }
});

这是一个 working example .请注意,我使用了 preventDefault事件对象的方法,仅仅是因为我认为这使得实际发生的事情更清楚。但是,return false 也可以。

关于javascript - 单击选择时停止 chrome 显示下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8062138/

相关文章:

javascript - Paper.js - 导出光栅

javascript - 无法覆盖 window.location 的 setter 和 getter

javascript - 基于多个下拉列表的自定义搜索

javascript - jQuery 新手,需要一些帮助

Javascript:创建脚本不起作用

javascript - 将http缓存解码为普通html页面

javascript - CSSOM 和 DOM 构造是在并行线程上进行的吗?

javascript - 我怎样才能让 gulp 对某些任务(单元测试、 vert 等)保持沉默?

ios - 在 iOS 上禁用移动 Chrome 的音频自动播放策略限制?

css - 在 Chrome 中将剪辑应用于视频