简体   繁体   English

JavaScript无法将焦点设置为ul中的第一个li元素

[英]JavaScript Not able to set focus to first li element within ul

I have below code: 我有下面的代码:

<ul id='someId'>
 <li class='someClass'>
 </li>
</ul>

I want to set focus on first li element within ul based on some condition. 我想根据某些条件将重点放在ul中的第一个li元素上。

My first attempt is like this: 我的第一次尝试是这样的:

var ul = document.getElementById('someId');           
var child = ul.childNodes[0];
child.focus();

My second attempt is like this : 我的第二次尝试是这样的:

var y = document.getElementsByClassName('someClass');
var aNode = y[0];
aNode.focus();

But none of the above works 但以上都没有

Any ideas? 有任何想法吗?

The problem is that you can't focus a non input element without setting tabIndex. 问题是如果不设置tabIndex,则无法聚焦非输入元素。

<li tabIndex="-1">...</li>

You can Try this fiddle: jsfiddle 你可以尝试这个小提琴: jsfiddle

An 'li' can't have focus, however an 'input' can, so you write yourself the following script: 'li'不能有焦点,但是'输入'可以,所以你自己编写以下脚本:

function installLI(obj){
       var ul = document.createElement('ul');
       obj.appendChild(ul);
       var li = document.createElement('li');
       var txt = document.createElement('input');
       li.appendChild(txt);
       ul.appendChild(li);
       txt.focus();
       li.removeChild(txt);
}

Where 'obj' is the object (like an editable div) that you're appending your list to. 'obj'是你要附加列表的对象(就像一个可编辑的div)。

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

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