简体   繁体   English

甜蜜警报2:如何在输入上自动对焦?

[英]sweet alert2: how to get autofocus on input?

using sweetalert2@8使用sweetalert2@8

Using sweet alert for a search box with below code.对带有以下代码的搜索框使用甜蜜警报。 Autofocus works on Chrome but not on Safari & Firefox.自动对焦适用于 Chrome,但不适用于 Safari 和 Firefox。 How can we fix this?我们怎样才能解决这个问题?

swal.fire({
    // title: "Search",
    type: "question",
    html: '<form id="searchForm" method="post" action="/search">' +
        "<input type='hidden' />" +
        '<input autofocus class="form-control" type="text" name="search_box" placeholder="Seach..."></form>',
    confirmButtonText: "Search",
    showLoaderOnConfirm: true,
    preConfirm: function (value) {
        document.getElementById("searchForm").submit();
        return new Promise(resolve => {
        })
    },
});

I suggest adding JavaScript code to polyfill the missing functionality you do not get in other browsers.我建议添加 JavaScript 代码来填充您在其他浏览器中没有的缺失功能。 Sweetalert2 also has a browser compatibility page here that says it's compatible in all major browsers. Sweetalert2 这里还有一个浏览器兼容性页面,上面说它兼容所有主要浏览器。 But also suggest using the following script tag to import the needed polyfill.但也建议使用以下脚本标签来导入所需的 polyfill。

<!-- Include a polyfill for ES6 Promises (optional) for IE11 -->
<script src="https://cdn.jsdelivr.net/npm/promise-polyfill@8/dist/polyfill.js"></script>

As far as the autofocus attribute, it is also supported by all major browser according to MDN .至于autofocus属性,根据MDN ,所有主要浏览器也支持它。 You could try using a JavaScript event when the alert is fired that sets the autofocus property.您可以尝试在触发设置 autofocus 属性的警报时使用 JavaScript 事件。

document.getElementById('myInput').autofocus = true;

You can also try to polyfill the autofocus property itself with this example here .您还可以尝试在此处使用此示例对 autofocus 属性本身进行 polyfill。

Another option here would be to use the native .focus() method on input inside didOpen parameter of SweetAlert2:这里的另一个选择是对.focus() didOpen参数内的输入使用原生的.focus()方法:

Swal.fire({
  ...
  didOpen: () => {
    Swal.getHtmlContainer().querySelector('.custom-input').focus()
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM