将select2与jQuery虚拟键盘配合使用

Using select2 with a jQuery Virtual Keyboard?

本文关键字:键盘 虚拟 select2 jQuery      更新时间:2023-09-26

我想知道是否有任何方法可以使用jQuery虚拟键盘在Select2选择栏中输入。

因为当您在Select2组件之外单击时,下拉列表会自动关闭。这不允许你使用任何基于网络的虚拟键盘。

如果你有想法,谢谢你的帮助!

Phew,花了一段时间!我为你做了一个简单的演示。只需点击选择,就会弹出一个键盘。

这里的技巧是,在用户单击select之前,select2搜索输入不存在于DOM中,因此我们使用select2:open事件在select2文本输入附加到DOM后找到它,然后将jquery虚拟键盘附加到它上。

// Make the Select2 select
$('#sel').select2({
  dropdownCssClass: 'keyboard_target_wrapper'
});
// We don't want to accidentally make multiple virtual keyboards
let kb_bound = false;
// Wait until the Select2 select is opened
// as the Select2 select input element
// might not be in the DOM yet
$('#sel').on('select2:open', function (e) {
  // Save the search input query
  let $select2SearchInput = $('.keyboard_target_wrapper')
        .find('.select2-search__field')
        
  // If we already have an initialized virtual keyboard
  // we just return it
  if(kb_bound) {
    $('.keyboard_target_wrapper')
    .find('.select2-search__field')
    .getkeyboard();
    return;
  }
  // Create the virtual keyboard
  $select2SearchInput.keyboard({
    openOn: 'focus',
    appendLocally: false, // Append to body
    appendTo: 'body',
    usePreview: false, // Hide the text preview on the keyboard
    reposition: true, // Make keyboard react to viewport changes
    layout: 'qwerty',
    css: {
      container: 'ui-widget-content ui-widget ui-corner-all ui-helper-clearfix',
      popup: ''
    },
    stopAtEnd: true,
    resetDefault: false,
    beforeInsert: function(e, keyboard, el, str) {
       // Must trigger keyup event on the Select2
       // search input manually, because
       // the virtual keyboard doesn't do it
       $select2SearchInput.keyup();
       
       // Just return the input text normally
       return str;
    },
  });
  
  kb_bound = true;
});
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/ui-lightness/jquery-ui.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/virtual-keyboard/1.30.4/css/keyboard.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script
  src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/virtual-keyboard/1.30.4/js/jquery.keyboard.min.js"></script>
<select id="sel">
  <option value="Cat">Cat</option>
  <option value="Dog">Dog</option>
  <option value="Bird">Bird</option>
  <option value="Fish">Fish</option>
  <option value="Dinosaur">Dinosaur</option>
</select>