sweet alert2:如何在输入时自动对焦?
sweet alert2: how to get autofocus on input?
使用以下代码对搜索框使用甜蜜警报。自动对焦适用于 Chrome 但不适用于 Safari 和 Firefox。我们该如何解决这个问题?
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 => {
})
},
});
我建议在 polyfill the missing functionality you do not get in other browsers. Sweetalert2 also has a browser compatibility page here 中添加 JavaScript 代码,表明它在所有主流浏览器中都兼容。但也建议使用以下脚本标签导入所需的 polyfill。
<!-- Include a polyfill for ES6 Promises (optional) for IE11 -->
<script src="https://cdn.jsdelivr.net/npm/promise-polyfill@8/dist/polyfill.js"></script>
至于 autofocus 属性,根据 MDN,所有主流浏览器也都支持它。您可以尝试在触发警报时使用 JavaScript 事件来设置自动对焦 属性.
document.getElementById('myInput').autofocus = true;
您也可以尝试使用此示例 here.
填充自动对焦 属性 本身
此处的另一个选项是在 SweetAlert2 的 didOpen
参数内的输入上使用本机 .focus()
方法:
Swal.fire({
...
didOpen: () => {
Swal.getHtmlContainer().querySelector('.custom-input').focus()
}
})
使用以下代码对搜索框使用甜蜜警报。自动对焦适用于 Chrome 但不适用于 Safari 和 Firefox。我们该如何解决这个问题?
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 => {
})
},
});
我建议在 polyfill the missing functionality you do not get in other browsers. Sweetalert2 also has a browser compatibility page here 中添加 JavaScript 代码,表明它在所有主流浏览器中都兼容。但也建议使用以下脚本标签导入所需的 polyfill。
<!-- Include a polyfill for ES6 Promises (optional) for IE11 -->
<script src="https://cdn.jsdelivr.net/npm/promise-polyfill@8/dist/polyfill.js"></script>
至于 autofocus 属性,根据 MDN,所有主流浏览器也都支持它。您可以尝试在触发警报时使用 JavaScript 事件来设置自动对焦 属性.
document.getElementById('myInput').autofocus = true;
您也可以尝试使用此示例 here.
填充自动对焦 属性 本身此处的另一个选项是在 SweetAlert2 的 didOpen
参数内的输入上使用本机 .focus()
方法:
Swal.fire({
...
didOpen: () => {
Swal.getHtmlContainer().querySelector('.custom-input').focus()
}
})