简体   繁体   English

js .focus()无法捕获对所需元素的关注

[英]Not able to capture focus on desired element by js .focus()

When i call $('#someelement').focus() it doesn't give any error message but practically not working. 当我调用$('#someelement').focus()它没有给出任何错误消息,但实际上不起作用。 When i try to get document.activeElement it still returning body element. 当我尝试获取document.activeElement它仍返回body元素。

Below is my console result: 以下是我的控制台结果:

在此处输入图片说明

You are calling .focus for #IncomeExpense_wrapper and that is <div> and div does not have focus event, only input elements does. 您正在为#IncomeExpense_wrapper调用.focus ,即<div>div没有focus事件,只有输入元素有。

Can't help further, because you provide no info on what focusing on div must do. 无法提供进一步的帮助,因为您没有提供有关div必须做什么的信息。

check this plunk it seems to be working fine. 检查这个花掉它似乎是工作的罚款。

<!DOCTYPE html>
<html>

  <head>
    <script data-require="jquery@3.0.0" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Hello Plunker!</h1>
    <input type="text" />
    <script>
  $('document').ready(function(){
    $('input').focus();
  })
    </script>
  </body>

</html>

If you want to focus a div. 如果要聚焦div。 i suggest you use this . 我建议你用这个 you see, it scrolls down to the div in question. 您会看到它向下滚动到相应的div。

<!DOCTYPE html>
<html>

  <head>
    <script data-require="jquery@3.0.0" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Hello Plunker!</h1>
    <h1>Hello Plunker!</h1>
    <h1>Hello Plunker!</h1>
    <h1>Hello Plunker!</h1><h1>Hello Plunker!</h1><h1>Hello Plunker!</h1><h1>Hello Plunker!</h1><h1>Hello Plunker!</h1><h1>Hello Plunker!</h1><h1>Hello Plunker!</h1><h1>Hello Plunker!</h1><h1>Hello Plunker!</h1><h1>Hello Plunker!</h1><h1>Hello Plunker!</h1><h1>Hello Plunker!</h1><h1>Hello Plunker!</h1><h1>Hello Plunker!</h1>
    <div id="somediv">this is the div</div>
    <script>
  $('document').ready(function(){
    window.location.hash = "#somediv";
  })
    </script>
  </body>

</html>

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

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