focus()不能在javascript或jquery中工作

时间:2017-07-16 16:55:36

标签: javascript jquery

我正在尝试使用javascript专注于输入元素。这是html。



<!DOCTYPE html>
<html>

<head>
  <style>
    input:focus {
      background-color: yellow;
    }
  </style>
</head>

<body>

  <p>Click inside the text fields to see a yellow background:</p>

  <form>
    First name: <input id="abc" type="text" name="firstname"><br>
  </form>

</body>

</html>
&#13;
&#13;
&#13;

当我使用鼠标手动点击时,我可以看到黄色背景。但是当我运行代码$(&#39;#abc&#39;)。focus()或document.getElementById(&#39; abc&#39;)。focus()我没有看到黄色背景。如何使用javascript模拟鼠标焦点?

3 个答案:

答案 0 :(得分:1)

我不知道你做错了什么,但是使用document.getElementById('abc').focus()访问输入元素,我能看到黄色背景。

const input = document.getElementById('abc');

input.focus();
<!DOCTYPE html>
<html>

<head>
  <style>
    input:focus {
      background-color: yellow;
    }
  </style>
</head>

<body>

  <p>Click inside the text fields to see a yellow background:</p>

  <form>
    First name: <input id="abc" type="text" name="firstname"><br>
  </form>

</body>

</html>

答案 1 :(得分:0)

在这里,你有它的工作。 希望它有所帮助。

$("#boton").click(function() {
  $("#abc").focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <style>
    input:focus {
      background-color: yellow;
    }
  </style>
</head>

<body>

  <p>Click inside the text fields to see a yellow background:</p>

  <form>
    First name: <input id="abc" type="text" name="firstname"><br>
  </form>
  <button id="boton"> Click Me to focus
</button>

</body>

</html>

答案 2 :(得分:0)

document.getElementById('abc').focus();如果你将这一行放在<script> in heml的头部。

或者如果您想使用jQuery,那么您需要将该代码放在document.ready函数中,如下所示:

$(document).ready(function(){
    $('#abc').focus();
});