gpt4 book ai didi

javascript - 无法聚焦使用 JS 创建的输入

转载 作者:行者123 更新时间:2023-12-03 01:06:57 25 4
gpt4 key购买 nike

我开始说我是新手,我的问题是我无法聚焦我在纯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");
}

最佳答案

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

关于javascript - 无法聚焦使用 JS 创建的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52354581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com