簡體   English   中英

JS scrollIntoView 不使用焦點()

[英]JS scrollIntoView not working with focus()

在單個 function 中,我試圖實現兩件事:

  1. 滾動到某個部分
  2. 專注於輸入

這是我的代碼:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM