Javascript sweet alert2:如何对输入进行自动聚焦?
使用 对包含以下代码的搜索框使用sweet alert。Autofocus适用于Chrome,但不适用于Safari和Firefox。我们如何解决这个问题Javascript sweet alert2:如何对输入进行自动聚焦?,javascript,sweetalert2,Javascript,Sweetalert2,使用 对包含以下代码的搜索框使用sweet alert。Autofocus适用于Chrome,但不适用于Safari和Firefox。我们如何解决这个问题 swal.fire({ // title: "Search", type: "question", html: '<form id="searchForm" method="post" action="/search">' + "<input type='hidden' />"
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 => {
})
},
});
swal.fire({
//标题:“搜索”,
键入:“问题”,
html:'+
"" +
'',
confirmButtonText:“搜索”,
请确认:正确,
预确认:功能(价值){
document.getElementById(“searchForm”).submit();
返回新承诺(解决=>{
})
},
});
我建议将JavaScript代码添加到其他浏览器中没有的功能中。Sweetalert2还有一个浏览器兼容性页面,上面说它在所有主要浏览器中都是兼容的。但也建议使用以下脚本标记导入所需的多边形填充
至于自动对焦属性,所有主要浏览器都支持该属性。您可以尝试在触发设置自动聚焦属性的警报时使用JavaScript事件
document.getElementById('myInput').autofocus = true;
您还可以尝试使用此示例来填充自动聚焦属性本身。这里的另一个选项是在SweetAlert2的
didOpen
参数内的输入上使用本机.focus()
方法:
Swal.fire({
...
didOpen:()=>{
Swal.getHtmlContainer().querySelector('.custom input').focus()
}
})
的确,根据MDN的说法,它应该可以工作,但仍然不行。添加document.getElementById(“searchForm”).autofocus=true或focus()或select()也没有帮助。还尝试了搜索框上的ID,而不是表单,Safari 12.0.2上的no luck感谢您的提示,根据您的输入找到了一个解决方案:使用名称搜索框(例如ID=“searchBoxId”)向输入添加第二个ID,然后(使用jquery)$(“#searchBoxId”)。focus();在swal.fire()调用完成之后,就可以了@戴维,我很高兴能帮助你走上正轨!