Prevent select dropdown from opening in FireFox an

2019-02-25 03:40发布

In jQuery, you can stop a <select> from opening it's dropdown menu by using event.preventDefault in the mousedown handler. Allowing you to replace the dropdown with something else while still retaining the original style of the form element.

This works fine in Chrome and MSIE, but in FireFox and Opera the dropdown appears regardless. (Not tested on Safari)

Example: http://jsfiddle.net/9cmEh/

The select element should look enabled and still respond to all user interaction as if enabled, but the dropdown should not be rendered. Instead the dropdown will be replaced by something custom rendered, such as including color swatches, icons or fonts, but the "custom dropdown" part is already done in my project.

Does anybody know how to make this work in all* browsers.

  • "All" meaning the recent versions of the five browsers mentioned.

5条回答
够拽才男人
2楼-- · 2019-02-25 04:04
$(function() {
    $('select').on('focus', function(e) {
        this.blur();
        window.focus();
    });
});

FIDDLE

Works in Firefox atleast, but does'nt seem to work in Chrome ?

EDIT

I could'nt come up with a decent way of detecting whether one method works or not, so did some browser sniffing instead. Not really the best way to do it, but the best I could come up with, and it does seem to work in the browsers I've tested :

$(function() {
    $('select').on('focus mousedown', function(e) {
        if ($.browser.webkit||$.browser.msie) {
            e.preventDefault();
        }else{
            this.blur();
            window.focus();
        }
    });
});​
查看更多
叛逆
3楼-- · 2019-02-25 04:06

This is a known bug: https://bugzilla.mozilla.org/show_bug.cgi?id=392863
It is currently inside firefox ESR32.

If like me you have a hidden <select> under your custom HTML/Javascript select and still want to keep the focus on that hidden <select> (for accessibility, tab navigation, arrow, enter ...).

Simply use z-index: -1.

.hidden-select {
  position: absolute;
  opacity: 0;
  filter: alpha(opacity=0);
  z-index: -1;
}
查看更多
该账号已被封号
4楼-- · 2019-02-25 04:20

disable not selected elements (options).

$('select option:not(:selected)').attr("disabled",true);

查看更多
一纸荒年 Trace。
5楼-- · 2019-02-25 04:22

thy this

               //e.stopPropagation works only in Firefox.
                  if (event.stopPropagation) {
                event.stopPropagation();
                event.preventDefault();
                 }

came from here link , This may help on the opera situation , it is slightly different question , but you may be able to get it to work

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-02-25 04:29

This should works in most case both on click and focus (with tab):

$('select').on('focus mousedown', function(e){
    e.stopPropagation();
    e.preventDefault();
    this.blur();
    window.focus();
});
查看更多
登录 后发表回答