【发布时间】:2021-11-23 17:37:56
【问题描述】:
我在这里有这段代码,它根据用户在输入中选择的内容,在 x 和 y 位置(高度和长度)创建一些巧克力块的网格(但不是真的),我希望它为它单独生产的每块巧克力分配一个新的 id(最好是 imgPos1、imgPos2 等)。我曾尝试参考其他帖子,但我完全无能为力。 我愿意接受对第三方框架(react 等)的任何建议。
HTML(和 js):
<html>
<body>
<div>
<form name='grid' id="grid">
<!-- Form to define the x size and y size of the grid made out of chocolate pieces -->
Desired Length: <input type='number' name='length' min=1 max=10 step=1 value=1 id="lengthInput" />
Desired Height: <input type='number' name='height' min=1 max=10 step=1 value=1 id="heightInput" />
<input type='button' value='Apply' class="button_Change" />
</form>
</div>
<div id='choc'></div>
<template>
<img id="imgPos" src="https://cdn.shopify.com/s/files/1/1061/1924/products/Chocolate_Bar_Emoji_large.png?" onclick='removeMe(this)' class='visible'>
</template>
<script type="text/javascript">
/* Script that creates the grid by cloning the chocolate image for x:length
and y:height */
// defines variables q,d,form using jquery
const d = document;
const q = (e, n = d) => n.querySelector(e);
const form = d.forms.grid;
// Listens for activity on the button depending on its state
document.querySelector('[type="button"]').addEventListener("click", (e) => {
let choc = q("#choc");
choc.innerHTML = "";
// Maxes out the values for height and length to 10 for practical reasons
if (form.height.value > 10) form.height.value = 10;
if (form.length.value > 10) form.length.value = 10;
// assigns chocolate image to length and height
for (let y = 0; y < form.height.value; y++) {
let div = d.createElement("div");
choc.appendChild(div);
for (let x = 0; x < form.length.value; x++) {
div.appendChild(q("#imgPos", q("template").content).cloneNode(true));
}
}
});
function removeMe(e) {
e.classList.remove("visible");
};
</script>
</body>
</html>
CSS
#grid {
top: 180px;
left: 350px;
position: absolute;
cursor: auto;
font-family: 'Press Start 2P', cursive;
font-size: 10px;
}
#imgPos {
display: block;
width : auto;
height: auto;
cursor: pointer;
position: relative;
width: 20px;
height: auto;
top: 0px;
left: 0px;
}
#choc {
display: grid;
grid-template-rows: 1fr 1fr;
margin-left: auto;
margin-right: auto;
top: 240px;
left: 340px;
position: absolute;
cursor: default;
}
#choc > div{
position: absolute;
width:50px;
display:block;
}
#choc > div > #imgPos{
float: left;
float: right;
clear:none;
width:50px;
display: inline-block;
}
#choc > div > #imgPos:not(.visible) {
opacity: 0;
cursor: default;
}
这是我用它制作的小提琴:
【问题讨论】:
标签: javascript html jquery css