简体   繁体   English

Javascript专注于DIV元素无法处理chrome

[英]Javascript Focus on DIV Element not working on chrome

Hi i want to Focus on div immediately after page load. 嗨我想在页面加载后立即关注div。 it's working perfect on Firefox, but not on chrome, it's not working. 它在Firefox上运行得很完美,但在Chrome上却没有,它不起作用。 this is my code : 这是我的代码:

https://jsfiddle.net/9yb2boxn/ https://jsfiddle.net/9yb2boxn/

 document.getElementById("focusme").focus(); 
 #focusme {width:400px; height:100px; overflow-y:scroll; } 
 <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> 

in Firefox when i run this code and i Press Down Arrow on keyboard, the div scrolling down. 在Firefox中,当我运行此代码并按下键盘上的向下箭头时,div向下滚动。 but not on chrome. 但不是铬。 why this problem occure? 为什么会出现这个问题?

i already try 我已经试过了

setTimeout(function() {

   document.getElementById("focusme").focus();

}, 1); 

still not working. 还是行不通。

please help. 请帮忙。 thanks 谢谢

If you want to make a non-focusable element focusable, you must add a tabindex attribute to it: 如果要使不可聚焦元素具有可聚焦性,则必须为其添加tabindex属性:

<div id="focusme" tabindex="1"></div>

Also, you can use the ID to reach it with the location hash. 此外,您可以使用ID通过位置哈希来访问它。 See the answer to your question here: Is it possible to focus on a <div> using javascript focus() function? 在这里查看你的问题的答案: 是否可以使用javascript focus()函数专注于<div>?

if you want to set focus to div through javascript you can use below code 如果你想通过javascript将焦点设置为div,你可以使用下面的代码

$("#focusme").attr("tabindex",-1).focus();

Hope this helps you. 希望这对你有所帮助。

  $("#focusme").attr("tabindex",-1).focus(); 
 #focusme {width:400px; height:100px; overflow-y:scroll; } 
 <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> 

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

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