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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30213603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:54:02  来源:igfitidea点击:

JavaScript Not able to set focus to first li element within ul

javascripthtml

提问by Sushil

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?

有任何想法吗?

回答by Luca Colonnello

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

回答by TheWizardOfTN

An 'li' can't have focus, however an 'input' can, so you write yourself the following script:

'li' 不能有焦点,但是 'input' 可以,所以你自己写了以下脚本:

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)。