我开始说我是新手,我的问题是我无法聚焦,这是我在纯Js中创建的输入字段,我只能右键单击或使用Tab来聚焦它。
谁能解释一下这里的问题在哪里,我怎么能用纯JS来解决它呢?
如您所见,我只是在DOM中添加了一些元素。
HTML:
<script src="nuovaVoce.js"></script>
<div id="cla" onclick="nuovavoce()">+ nuova voce</div>
function nuovavoce() {
var div = document.createElement('div');
var caselle = document.createElement("form");
var input1 = document.createElement("input");
var input2 = document.createElement("input");
document.getElementById("cla").appendChild(div);
div.style.backgroundColor = "black";
div.style.position = "absolute";
div.style.left = "0px";
div.style.width = "100%";
div.style.height = "100%";
div.style.top = "0px";
div.appendChild(caselle);
caselle.setAttribute("method", "post");
caselle.setAttribute("enctype", "multipart/form-data");
caselle.setAttribute("onsubmit", "");
caselle.appendChild(input1);
input1.style.position = "static";
input1.style.width = "80%";
input1.style.height = "";
input1.style.marginLeft = "";
input1.style.marginTop = "";
input1.setAttribute("name", "titolo");
input1.setAttribute("type", "text");
caselle.appendChild(input2);
input2.style.position = "static";
input2.style.width = "80%";
input2.style.height = "";
input2.style.marginLeft = "";
input2.style.marginTop = "";
input2.setAttribute("type", "submit");
input2.setAttribute("name", "submit_categoria");
}
答案 0 :(得分:1)
我建议使用.focus()方法。在功能结束时,您需要添加:
add input1.focus();
function nuovavoce() {
var div = document.createElement('div');
var caselle = document.createElement("form");
var input1 = document.createElement("input");
var input2 = document.createElement("input");
document.getElementById("cla").appendChild(div);
div.style.backgroundColor = "black";
div.style.position = "absolute";
div.style.left = "0px";
div.style.width = "100%";
div.style.height = "100%";
div.style.top = "0px";
div.appendChild(caselle);
caselle.setAttribute("method", "post");
caselle.setAttribute("enctype", "multipart/form-data");
caselle.setAttribute("onsubmit", "");
caselle.appendChild(input1);
input1.style.position = "static";
input1.style.width = "80%";
input1.style.height = "";
input1.style.marginLeft = "";
input1.style.marginTop = "";
input1.setAttribute("name", "titolo");
input1.setAttribute("type", "text");
caselle.appendChild(input2);
input2.style.position = "static";
input2.style.width = "80%";
input2.style.height = "";
input2.style.marginLeft = "";
input2.style.marginTop = "";
input2.setAttribute("type", "submit");
input2.setAttribute("name", "submit_categoria");
input1.focus();
}
<div id="cla" onclick="nuovavoce()">+ nuova voce</div>