[英]Javascript Focus() function not working
我有一个文本框,我想将焦点放在它上面,但它不起作用。
document.getElementById("txtCity").focus();
任何的想法?
如果有人在搜索时遇到与我类似的情况......我必须在我的div
可以接收focus()
之前设置一个tabindex
属性:
featured.setAttribute('tabindex', '0');
featured.focus();
console.log(document.activeElement===featured); // true
(我在这里找到了答案: 让 div 元素获得焦点)
当然,在将焦点设置到子元素之前,请确保 body 元素已准备就绪。
也许您在呈现输入元素之前调用了 JavaScript? 将输入元素放在 JavaScript 之前,或者等到页面加载完毕后再触发 JavaScript。
按照这个顺序,它工作得很好:
<input type="text" id="test" />
<script type="text/javascript">
document.getElementById("test").focus();
</script>
在jQuery 中,您可以将代码放在.ready()
方法中,以便在 DOM 完全加载时首先执行代码:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#test").focus();
// document.getElementById("test").focus();
});
</script>
我也遇到了同样的问题。要解决这个问题,请将您的代码放在 setTimeout 函数中。
function showMeOnClick() {
// Set text filed focus after some delay
setTimeout(function() { jQuery('#searchTF').focus() }, 20);
// Do your work.....
}
尝试将其包装到文档就绪函数中,并确保包含 jquery。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#test").focus();
});
</script>
<div id="txtROSComments" contenteditable="true" onkeyup="SentenceCase(this, event)"style="border: 1px solid black; height: 200px; width: 200px;">
</div>
<script type="text/javascript">
function SentenceCase(inField, e) {
debugger;
var charCode;
if (e && e.which) {
charCode = e.which;
} else if (window.event) {
e = window.event;
charCode = e.keyCode;
}
if (charCode == 190) {
format();
}
}
function format() {
debugger; ;
var result = document.getElementById('txtROSComments').innerHTML.split(".");
var finaltxt = "";
var toformat = result[result.length - 2];
result[0] = result[0].substring(0, 1).toUpperCase() + result[0].slice(1);
if (toformat[0] != " ") {
for (var i = 0; i < result.length - 1; i++) {
finaltxt += result[i] + ".";
}
document.getElementById('txtROSComments').innerHTML = finaltxt;
alert(finaltxt);
abc();
return finaltxt;
}
if (toformat[0].toString() == " ") {
debugger;
var upped = toformat.substring(1, 2).toUpperCase();
var formatted = " " + upped + toformat.slice(2);
for (var i = 0; i < result.length - 1; i++) {
if (i == (result.length - 2)) {
finaltxt += formatted + ".";
}
else {
finaltxt += result[i] + ".";
}
}
}
else {
debugger;
var upped = toformat.substring(0, 1).toUpperCase();
var formatted = " " + upped + toformat.slice(1);
for (var i = 0; i < result.length - 1; i++) {
if (i == (result.length - 2)) {
finaltxt += formatted + ".";
}
else {
//if(i
finaltxt += result[i] + ".";
}
}
}
debugger;
document.getElementById('txtROSComments').value = finaltxt;
return finaltxt;
}
</script>
<script type="text/javascript">
function abc() {
document.getElementById("#txtROSComments").focus();
}
它在这个例子中工作正常http://jsfiddle.net/lmcculley/rYfvQ/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.