简体   繁体   English

将元素添加到DOM后如何立即对其进行聚焦

[英]How to immediately focus an element when it is added to the DOM

I have a dropdown list which shows up on a button click. 我有一个下拉列表,单击后会显示出来。 This dropdown list is not available in the DOM until the button is clicked. 在单击按钮之前,此下拉列表在DOM中不可用。 How can I get the focus on the first list item of this dropdown list as soon as it is added to the DOM. 将其添加到DOM后,如何立即将注意力集中在此下拉列表的第一个列表项上。

Thank you. 谢谢。

For ex: If your dropdown element id is "selectstate", then you could do it using getElementById 例如:如果您的下拉列表元素ID为“ selectstate”,则可以使用getElementById进行操作

   <select id="state" name="state">
<option value="AB">AB</option>
<option value="AC">AC</option>
</select>


window.onload = function() {

    document.getElementById("state").focus();
};

Below snippet will help you to create a dropdown button on DOM then focus it. 以下代码段将帮助您在DOM上创建一个下拉按钮,然后将其聚焦。 Of course you've to improve it. 当然,您必须改进它。

 createDropdown = function(optsArray) { let dd = document.createElement("select"); dd.setAttribute("id", "foo"); for(var i =0; i<optsArray.length; i++) { let opt = document.createElement("option"); opt.setAttribute("value", i); let optText = document.createTextNode(optsArray[i]); opt.appendChild(optText); dd.appendChild(opt); } let cnt = document.getElementById("dropdown-container"); cnt.innerHTML=""; cnt.appendChild(dd); dd.focus(); } document.querySelector("button").addEventListener("click", function() { let opts = ["Marx", "Engels", "Lenin", "Gramsci", "Althusser", "Zizek"]; createDropdown(opts); }) 
 #dropdown-container{ margin-top: 700px; } 
 <button>Click me to load dropdown and focus it</button> <div id="dropdown-container"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM