嗨我想在页面加载后立即关注div。它在Firefox上运行得很完美,但在Chrome上却没有,它不起作用。这是我的代码:
https://jsfiddle.net/9yb2boxn/
document.getElementById("my_input").focus();
document.getElementById("focusme").focus();
#focusme {width:400px; height:100px; overflow-y:scroll; }
在Firefox中,当我运行此代码并按下键盘上的向下箭头时,div向下滚动。但不是铬。为什么会出现这个问题?
我已经尝试了
<div id="focusme">
focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me
</div>
仍然无法正常工作。
请帮忙。感谢
答案 0 :(得分:10)
如果你想让一个不可聚焦的元素可聚焦,你必须为它添加一个tabindex属性:
<div id="focusme" tabindex="1"></div>
此外,您可以使用ID通过位置哈希来访问它。 在这里查看您的问题的答案: Is it possible to focus on a <div> using javascript focus() function?
答案 1 :(得分:1)
如果你想通过javascript将焦点设置为div,你可以使用下面的代码
$("#focusme").attr("tabindex",-1).focus();
希望这会对你有所帮助。
$("#focusme").attr("tabindex",-1).focus();
&#13;
#focusme {width:400px; height:100px; overflow-y:scroll; }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<div id="focusme">
focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me
</div>
&#13;