专注于自动提交的输入吗?

时间:2020-02-28 14:17:26

标签: jquery wordpress forms focus input-field

我有一个自定义模式的javascript,其中包含一个自定义搜索输入, 激活自定义模式后如何使输入自动对焦而无需鼠标单击以激活它?

我搜索并检查了Bootstrap Modal的所有工作方式。

代码下方:

var twentytwenty = twentytwenty || {};

twentytwenty.searchToggles = {
  init: function() {
    this.toggleSearch();
    this.untoggleSearch();
    this.untoggleOnEscapeKeyPress();
  },
  toggleSearch: function() {
    var $this = this;
    document.querySelectorAll('.toggle.search-toggle.desktop-search-toggle')
    $('.custom-modal').on('.custom-modal.open', function() {
      $(this).find('input:first').focus();
    }).forEach(function(element) {
      element.addEventListener('click', function(event) {
        event.preventDefault();
        $this.toggleClass('open', 'close');
      });
    });
  },
  untoggleSearch: function() {
    var $this = this;
    document.querySelectorAll('.custom-close').forEach(function(element) {
      element.addEventListener('click', function(event) {
        event.preventDefault();
        $this.toggleClass('close', 'open');
      });
    });

    document.addEventListener('click', function(event) {
      if (event.target.className == 'custom-modal custom-search-popup open') {
        $this.toggleClass('close', 'open');
      }
    });
  },
  // Close toggle on escape key press
  untoggleOnEscapeKeyPress: function() {
    var $this = this;
    document.addEventListener('keyup', function(evt) {
      if (evt.keyCode == 27) {
        $this.toggleClass('close', 'open');
      }
    });
  },
  toggleClass: function(add, remove) {
    var el = document.getElementsByClassName('custom-modal custom-search-popup');
    for (var i = 0; i < el.length; i++) {
      el[i].classList.add(add);
      el[i].classList.remove(remove);
    }
  }
};

function add(add, remove) {
  console.log('add');
}

/**
 * Is the DOM ready
 *
 * this implementation is coming from https://gomakethings.com/a-native-javascript-equivalent-of-jquerys-ready-method/
 *
 * @param {Function} fn Callback function to run.
 */
function twentytwentyDomReady(fn) {
  if (typeof fn !== 'function') {
    return;
  }

  if (
    document.readyState === 'interactive' ||
    document.readyState === 'complete'
  ) {
    return fn();
  }

  document.addEventListener('DOMContentLoaded', fn, false);
}

twentytwentyDomReady(function() {
  twentytwenty.searchToggles.init();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="get" id="search-form-alt" action="'. esc_url(home_url('/')) .'">
  <input type="text" name="s" autofocus id="s" placeholder="Type your search words here...">
  <input type="submit" class="fa fa-search" id="searchsubmit" value="" />
</form>

0 个答案:

没有答案
相关问题