我可以将变量设置为输入元素的最大值吗?
Can I set a variable as a max value on an input element?
我的页面上有一个 canvas 和几个 input[type="range"]
标签来玩它。我需要的是将 max
属性的值设置为 JS 变量。
我试过:
- 直接在HTML中设置为:
<input type="range" id="y" max="canvas.height">
- 在Javascript中设置,但我不知道如何在JS中设置
max
属性,所以我尝试了类似的方法:id("y").max = canvas.height; // id() is my utility function
所以基本上我要问你的是告诉我我做错了什么,或者如何在 JS 中设置 max
/min
。
我看过这里:
- https://www.w3schools.com/tags/att_input_min.asp
- https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/max
P.S。我知道如何在 jQuery 中实现这一点(使用 .attr),但我不想仅仅因为一个属性就将 jQuery 带到我的项目中。
请记住,由于 jQuery 是基于 vanilla JS 构建的,因此 jQuery 所做的任何事情都可以用普通的 JavaScript 来完成。在这个特定的例子中,你正在寻找 Element.setAttribute
:
const myInput = document.querySelector('some css selector that matches your input'); // you can get this any way you want
myInput.setAttribute('max', canvas.height);
我认为 HTML 中没有直接引用 JS 变量的方法,所以我相信 JS 是您的答案。也就是说,也许另一张海报可以提供一些不同的方法。
请求检查 this link。我希望这会有所帮助。
所以你可以这样做:
Element.setAttribute('max', 'canvas.height');
我的页面上有一个 canvas 和几个 input[type="range"]
标签来玩它。我需要的是将 max
属性的值设置为 JS 变量。
我试过:
- 直接在HTML中设置为:
<input type="range" id="y" max="canvas.height">
- 在Javascript中设置,但我不知道如何在JS中设置
max
属性,所以我尝试了类似的方法:id("y").max = canvas.height; // id() is my utility function
所以基本上我要问你的是告诉我我做错了什么,或者如何在 JS 中设置 max
/min
。
我看过这里:
- https://www.w3schools.com/tags/att_input_min.asp
- https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/max
P.S。我知道如何在 jQuery 中实现这一点(使用 .attr),但我不想仅仅因为一个属性就将 jQuery 带到我的项目中。
请记住,由于 jQuery 是基于 vanilla JS 构建的,因此 jQuery 所做的任何事情都可以用普通的 JavaScript 来完成。在这个特定的例子中,你正在寻找 Element.setAttribute
:
const myInput = document.querySelector('some css selector that matches your input'); // you can get this any way you want
myInput.setAttribute('max', canvas.height);
我认为 HTML 中没有直接引用 JS 变量的方法,所以我相信 JS 是您的答案。也就是说,也许另一张海报可以提供一些不同的方法。
请求检查 this link。我希望这会有所帮助。
所以你可以这样做:
Element.setAttribute('max', 'canvas.height');