2017-07-16 55 views
0

我想着重于使用JavaScript的输入元素。这是html。焦点()不工作在JavaScript或jQuery

<!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>

当我手动点击使用鼠标,我可以看到黄色的背景。但是当我运行代码$('#abc')。focus()或document.getElementById('abc')。focus()我看不到黄色背景。如何使用JavaScript模拟鼠标焦点?

+2

你的代码的工作,这里是[小提琴](https://开头的jsfiddle .net/kukicvladimir/1n5o4qkf /)我无法重现问题 –

+0

代码正在工作,请尝试检查您是否在javascript中没有任何语法错误或为js文件命名空间路径 –

+0

如果这是所有代码,那么就没有包括jQuery? – mrbubbles

回答

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

在这里,你有它的工作。 希望它有帮助。如果您在HEML的头部分,就把这行中<script>

$("#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>

0

document.getElementById('abc').focus();会工作。

或者,如果你想用jQuery做到这一点,那么你需要把这些代码中的document.ready功能是这样的:

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

不是 - 两种说法都是错误的。 –

+0

@ freedomn-m,你能告诉我如何? –

+0

Ok.1如果你把这个脚本放在'head'中,它会在body生成之前运行(这就是为什么我们在jquery中使用doc.ready的原因)。所以1不会工作,因为'#abc'元素不会存在。 2.您不需要*将jquery代码放入doc.ready中,它会按照1,在页面中出现时运行。如果你在主体的最后放置了$('#abc')。focus()'(没有文档就绪),它仍然可以工作。我们使用doc.ready,以便代码不依赖于其在本体内的位置。 –