【问题标题】:How to add input fields that will update once values are entered?一旦输入值,如何添加将更新的输入字段?
【发布时间】:2025-12-04 18:50:02
【问题描述】:

我正在创建一个用于根据用户输入参数创建 SVG 图形的 javascript,并且我想添加一些可以接受数字输入和字符串输入的输入字段。想象一下:

Graph height: [600]
Background Color: [#dfe0ef]
...

^ 想象一下页面上的文本字段而不是括号。

我想知道是否应该为此使用表单。但是我不需要向服务器发送任何数据,所以如果可能的话,我想只使用 js 来保持简单。每次输入新值时,我都需要在浏览器中更新 SVG 图。

到目前为止,我发现的所有示例都比我需要的要复杂,因此很难将它们用作参考。所以希望这里有人能解释一下:如何添加输入字段,一旦输入就会更新脚本(以及 SVG)?

谢谢

更新:我有一个使用 DIV 标签的概念验证。所以现在剩下的就是用 SVG 替换 DIV 并用更多参数填充它。

<!DOCTYPE html>
<html>
<body>

<p>Please specify a width, a height, and a background color.</p>

<p>Width:</p>
<input 
	id="i_width" 
	type="number" 
	min="1" 
	max="1024" 
	value="200"
	oninput="render()"
>
<br />

<p>Height:</p>
<input 
	id="i_height" 
	type="number" 
	min="1" 
	max="1024" 
	value="100" 
	oninput="render()"
>
<br />

<p>Background Color:</p>
<input
	id="i_bg_color" 
	type="text" 
	value="#bada55" 
	oninput="render()"
>

<p id="text_output"></p>
<br />
<div id="container_output"></div>

<script>
//Gets all variable values from input fields.
//Input IDs are "i_" + "var_name"
function render() {
  var width = document.getElementById("i_width").value;
	var height = document.getElementById("i_height").value;
	var bg_color = document.getElementById("i_bg_color").value;

//text_output
document.getElementById("text_output").innerHTML = "The width is " + width + ", and the height is " + height + ". The background color is " + bg_color + ".";

//container_output
document.getElementById("container_output").innerHTML = `
<div 
	style="
		width:${width}px;
		height:${height}px;
		background-color:${bg_color};
	">
</div>
`
}
</script>

</body>
</html>

  

【问题讨论】:

  • 创建&lt;input&gt; 元素。使用 `.value 获取输入数字。

标签: javascript html svg


【解决方案1】:

您可以像这样在 JavaScript 中为 oninput 事件附加侦听器:

text_field_element.addEventListener('oninput', () => {
    //redraw 
}

其中text_field_element 是一些&lt;input&gt; 元素。

没有看到有关您的实现的更多详细信息,我不确定如何重新绘制实际图表,尽管附加该侦听器应该会让您踏上第一步。

【讨论】:

  • 您提供的关于 oninput Event 的 w3schools 链接最终帮助我理解。谢谢!
【解决方案2】:

我会这样做:

theHeight.addEventListener("input", () => {
  theRect.setAttributeNS(null, "height", theHeight.value);
});
svg{border:1px solid; width:90vh}
<svg viewBox="0 0 100 50">
     <rect id="theRect" x="20" y="10" width="60" height="30" fill="skyBlue" />
</svg>

<input id="theHeight" type="number" min="1" max="40" value="30" />

【讨论】: