首页 > 解决方案 > 无法聚焦使用 JS 创建的输入

问题描述

我开始说我是新手,我的问题是我无法聚焦在纯 Js 中创建的输入字段,我只能右键单击或使用 Tab 聚焦它。
谁能解释我这里的问题在哪里,我怎么能用简单的纯JS来解决它?
如您所见,我只是在我的 DOM 中添加了一些元素。

HTML:

<script src="nuovaVoce.js"></script>
<div id="cla" onclick="nuovavoce()">+ nuova voce</div>

JAVASCRIPT:

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");
}

标签: javascripthtmlinputfocus

解决方案


我建议使用.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>


推荐阅读