在p5.js中如何将输入框的值转换为h3等HTML元素?
解决方案
根因说明
你代码中声明的yourName变量仅做了定义,未初始化绑定对应的DOM元素,调用.html()方法时没有作用目标,因此无法生效。
实现代码
你可以提前在setup阶段创建h3元素,绑定到yourName变量,点击按钮时直接更新该元素内容即可,同时可以给h3设置自定义类名方便后续CSS样式控制:
let inputName, bttName, yourName; function setup() { let inputDiv = createDiv(); inputDiv.id("input-section"); inputDiv.parent("sobre"); inputName = createInput(); inputName.addClass("input-name"); inputName.parent("input-section"); bttName = createButton('enter'); bttName.addClass('btt-name'); bttName.parent("input-section"); bttName.mousePressed(sendName); // 初始化h3元素,添加自定义类 yourName = createElement('h3'); yourName.addClass('custom-h3-style'); yourName.parent("input-section"); // 可替换为你需要放置h3的父容器id } function sendName() { let userName = inputName.value(); yourName.html(userName); }
如果需要每次点击生成新的h3元素而非复用同一个,可以用数组存储所有生成的元素,方便后续管理:
let inputName, bttName, nameH3List = []; // 省略setup中输入框、按钮的创建代码,和之前一致 function sendName() { let userName = inputName.value(); let newH3 = createElement('h3', userName); newH3.addClass('custom-h3-style'); newH3.parent("input-section"); nameH3List.push(newH3); }
样式控制
直接针对你设置的自定义类编写CSS规则即可,示例:
.custom-h3-style { color: #2c3e50; font-size: 20px; margin: 12px 0; }
内容的提问来源于stack exchange,提问作者llelell
相关产品推荐
相关产品推荐

