Javascript HTML 范围:动态设置值属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12377590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:51:01  来源:igfitidea点击:

HTML range: set value attribute dynamically

javascripthtmlrange

提问by user1639762

Good evening!!

晚上好!!

I'm using HTML input type range to create a slidebar. I would like to dynamically change the attribute "value" (default position of the cursor) before displaying the slidebar.

我正在使用 HTML 输入类型范围来创建滑动条。我想在显示滑动条之前动态更改属性“值”(光标的默认位置)。

I can retrieve the value I need (from localStorage) but I don't manage to set it!!

我可以检索我需要的值(从 localStorage),但我无法设置它!!

Here is the range object:

这是范围对象:

<input type="range" min="0" max="1050" value="0" step="30"  onchange="showValue(this.value); changeScrollBar(this.value);"/>

Now it is set to 0 but I would like to use a variable to change it (i.e I'll set a new variable foo=localStorage.getItem("foo2") then I would like to use value=foo in range)!

现在它被设置为 0 但我想使用一个变量来改变它(即我将设置一个新变量 foo=localStorage.getItem("foo2") 然后我想在范围内使用 value=foo)!

Any clue?

有什么线索吗?

Thanks a lot!!!

非常感谢!!!

回答by jfriend00

You get the DOM element for the <input>tag and then use:

您获取<input>标签的 DOM 元素,然后使用:

elem.value = foo;


If you add an ID to the input tag like this:

如果您将 ID 添加到输入标签,如下所示:

<input id="mySlider" type="range" min="0" max="1050" value="0" step="30"  onchange="showValue(this.value); changeScrollBar(this.value);"/>

Then, you can do the whole thing like this:

然后,你可以像这样完成整个事情:

var input = document.getElementById("mySlider");
input.value = localStorage.getItem("foo2");