简体   繁体   English

如何在 javascript 中使用范围 slider 更新值(更改时)?

[英]How to use range slider updated values (on change) in javascript?

Let say i have created a slider and i am changing the value of slider using mouse.假设我创建了一个 slider 并且我正在使用鼠标更改 slider 的值。 How can i use these values as variable in global scope, this variable should change to updated value when i changed the slider. I want to use the slider value in canvas to update my object.我如何将这些值用作全局变量 scope,当我更改 slider 时,此变量应更改为更新值。我想使用 canvas 中的 slider 值来更新我的 object。

HTML
<input id="slider" type="range" min="0" max="100" value="50" step="1" onchange="myFn()" >

JS
function myFn(){
  let a = document.getElementbyId("slider").value;
  console.log(a); //value change here how value is use outside the function.
}

I think document.getElementById is getting invoked for every function call which is not an ideal.我认为 document.getElementById 被每个 function 调用调用,这不是一个理想的。 You can do like below.你可以像下面那样做。

// global scope
let inputEl = document.getElementById("slider");
let a;
function myFn() {
   a = inputEl.value;
}
console.log(a); // as let is block scoped it can be accessed outside of the function or instead of let you can var keyword

Your code is being misspelled: document.getElementById, letter b needs to be capitalized您的代码拼写错误:document.getElementById,字母 b 需要大写

Please try again with HTML:请使用 HTML 重试:

<input id="slider" type="range" min="0" max="100" value="50" step="1">

and javascript和 javascript

let slider = document.getElementById('slider');
    
slider.onchange = function(){
  console.log(this.value)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM