【发布时间】: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>
【问题讨论】:
-
创建
<input>元素。使用 `.value 获取输入数字。
标签: javascript html svg