Prevent select2 from autmatically focussing its search-input when dropdown is opened

后端 未结 10 518
野性不改
野性不改 2021-01-11 16:02

I\'m looking for a way to prevent select2\'s search-input being automatically focussed when the select2-dropdown is opened. I know this is select2\'s intended default behavi

10条回答
  •  佛祖请我去吃肉
    2021-01-11 16:27

    Although @Choma's answer is fine, it will alter the select2 default behavior on both desktop and mobile devices.

    I had to find a solution for a responsive website: prevent the auto-focus of the search input only on mobile devices, and keep the default behaviour on desktops.

    In order to detect the mobile devices, I've used Modernizr library, which can test for the existence of Touch Events in the browser.

    We can use Modernizr.touch on Modenizr v2, which will return true if touch events are supported, or false otherwise.

    So we can modify @Choma's answer like this:

    $('select').on('select2:open', function() {
      if (Modernizr.touch) {
        $('.select2-search__field').prop('focus', false);
      }
    });
    

    Demo:

    https://codepen.io/andreivictor/full/QmKxOw/

    Tested on:

    • Desktop: IE 11, Chrome, Firefox, Opera, Safari
    • Android 4.2.2
    • Android 5.0.1 (Samsung Galaxy S4)
    • Android 6.0.1 (Samsung Galaxy S7 Edge)
    • iOS 11.2.5 (iPhone 8)
    • iOS 10.3.2 (iPhone 6 Plus)
    • iOS 10.3.2 (iPad Mini 3)

提交回复
热议问题