[英]How to set focus on an image on page load
有沒有辦法將焦點放在頁面加載上? 我找到了說明使用autofocus
屬性的文檔,但文檔說該屬性僅適用於input
、 button
、 textarea
和select
。
謝謝。
您可以在窗口 onload 上嘗試scrollIntoView
方法
window.onload=function(){
document.getElementById("ID_OF_IMAGE").scrollIntoView();
}
我認為您正在尋找類似的東西:
window.addEventListener('load', function() {
document.querySelector(".classFromImage").focus();
})
您可以做的是搜索具有autofocus
屬性的img
元素,並在讀取 DOM 后設置焦點。 您還需要設置tabindex
以使其正常工作。
我只會搜索img[autofocus]
,這樣您就不會過多地使用默認行為。
window.addEventListener('DOMContentLoaded', function() { let elm = document.querySelector("img[autofocus]") if (elm) { elm.focus() } })
img { width: 100px; height: 100px; display: inline-block; } :focus { border: 4px solid red; }
<img autofocus tabindex="0">
您可以通過將 tabindex="0" 屬性添加到標簽並在 js 中使用 focus() 方法來聚焦不可聚焦的元素。
<img class="focusable" tabindex="0" src="#"/>
window.addEventListener('load', function() {
document.querySelector(".focusable").focus();
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.