[英]JS scrollIntoView not working with focus()
在單個 function 中,我試圖實現兩件事:
這是我的代碼:
function search() {
document.getElementById("searchbar").style.display = "block";
document.getElementById("flex").style.display = "none";
document.getElementById("books").scrollIntoView({behavior: 'smooth'});
key();
};
function key(){
document.getElementById("searchbox").focus();
};
滾動在這里不起作用。 如果我刪除“鑰匙”function,它可以工作。
不需要單獨的“鑰匙”function,但我試過了。
id 為“searchbox”的輸入被放置在“position:fixed”分區內。 它在“書籍”部分之外。
您可以簡單地顛倒調用這些方法的順序。
function search() { document.getElementById("searchbox").focus(); document.getElementById("books").scrollIntoView({behavior: 'smooth'}); }; document.getElementById("btn").onclick = search;
#books { margin-top: 300vh; }
<button id="btn">search</button> <input id="searchbox" value="#searchbox"> <div id="books">Some books</div>
發生的情況是調用Element.focus()
將自動使您的瀏覽器滾動到該元素。 這樣做,它將取消之前對scrollIntoView
的調用。 通過反轉調用順序, scrollIntoView
將取消focus
滾動,這正是您想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.