簡體   English   中英

甜蜜警報2:如何在輸入上自動對焦?

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

使用sweetalert2@8

對帶有以下代碼的搜索框使用甜蜜警報。 自動對焦適用於 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 => {
        })
    },
});

我建議添加 JavaScript 代碼來填充您在其他瀏覽器中沒有的缺失功能。 Sweetalert2 這里還有一個瀏覽器兼容性頁面,上面說它兼容所有主要瀏覽器。 但也建議使用以下腳本標簽來導入所需的 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 ,所有主要瀏覽器也支持它。 您可以嘗試在觸發設置 autofocus 屬性的警報時使用 JavaScript 事件。

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

您還可以嘗試在此處使用此示例對 autofocus 屬性本身進行 polyfill。

這里的另一個選擇是對.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