Html HTML5 范围的 onChange 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5165579/
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-29 07:03:16  来源:igfitidea点击:

onChange event for HTML5 range

htmlformsrangeonchange

提问by WilliamMayor

Currently the onChange event on my range inputs is firing at each step.

目前,我的范围输入上的 onChange 事件在每一步都触发。

Is there a way to stop this event from firing until the user has let go of the slider?

有没有办法阻止此事件触发,直到用户松开滑块?

I'm using the range to create a search query. I want to be able to run the search every time the form is changed but issuing a search request at each step of the slider's movement is too much.

我正在使用范围来创建搜索查询。我希望能够在每次更改表单时运行搜索,但是在滑块移动的每一步发出搜索请求太多了。



Here's the code as it stands:

这是它的代码:

HTML:

HTML:

<div id="page">
    <p>Currently viewing page <span>1</span>.</p>
    <input class="slider" type="range" min="1" max="100" step="1" value="1" name="page" />
</div>

JavaScript:

JavaScript:

$(".slider").change(function() {
    $("#query").text($("form").serialize());
});

Does that help?

这有帮助吗?

回答by kravits88

Use for final selected value:

用于最终选定的值:

 $(".slider").on("change", function(){console.log(this.value)});

Use to get incremental value as sliding:

用于在滑动时获取增量值:

$(".slider").on("input", function(){console.log(this.value)});

回答by Arwyn

Bit late, but I had the same problem the other day. Here is my solution using jQuery bind/trigger:

有点晚了,但前几天我遇到了同样的问题。这是我使用 jQuery 绑定/触发器的解决方案:

(function(el, timeout) {
    var timer, trig=function() { el.trigger("changed"); };
    el.bind("change", function() {
        if(timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(trig, timeout);
    });
})($(".slider"), 500);

Now just bind your function to the 'changed' event instead.

现在只需将您的函数绑定到 'changed' 事件。

回答by Toastar

Bah!

呸!

Use onmouseupevent Rather then onChange

使用onmouseup事件而不是onChange

回答by RoToRa

One problem is that AFAIK the HTML5 doesn't define when the onchangeevent is supposed to fire, so it is most likely different from browser to browser. And you also have to consider, that a browser doesn't actually have to render an input type=rangeas a slider.

一个问题是 AFAIK HTML5 没有定义onchange事件应该何时触发,因此它很可能因浏览器而异。而且您还必须考虑,浏览器实际上不必将 呈现input type=range为滑块。

Your only choice is that you have to build in a mechanism to make sure that your search isn't triggered too often, for example, check if a search is currently running and abort if it is, or make sure that searches are triggered at a maximum of every xseconds.

您唯一的选择是您必须建立一种机制来确保您的搜索不会被过于频繁地触发,例如,检查搜索当前是否正在运行并中止,或者确保搜索在某个时间触发。最大每x秒。

Quick example for the latter (just a quick hack, untested).

后者的快速示例(只是一个快速的黑客,未经测试)。

var doSearch = false;

function runSearch() {
   // execute your search here 
}

setInterval(function() {
  if (doSearch) {
     doSearch = false;
     runSearch();
  }
}, 2000); // 2000ms between each search.

yourRangeInputElement.onchange = function() { doSearch = true; }

回答by RoToRa

Pure JS here:

纯JS在这里:

myInput.oninput = function(){
    console.log(this.value);
}

or

或者

myInput.onchange = function(){
    console.log(this.value);
}

回答by mons droid

gravediggin but if you need it check js throttleor debouncefunctions

Gravediggin 但如果你需要它检查 js油门去抖动功能

Usage:

用法:

//resize events gets processed 500ms after the last Event
addEventListener("resize", _debounce(function(){ foo;}, 500));

//resize events get processed every 500ms
addEventListener("resize", _throttle(function(){ foo;}, 500));

Code:

代码:

/*waits 'delay' time after the last event to fire */
_debounce = function(fn, delay) {
    var timer = null;
    return function() {
        var context = this,
            args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function() {
            fn.apply(context, args);
        }, delay);
    };
};


/* triggers every 'treshhold' ms, */
_throttle = function(fn, threshhold, scope) {
    threshhold = threshhold || 250;
    var last,
        deferTimer;
    return function() {
        var context = scope || this;

        var now = +new Date(),
            args = arguments;
        if (last && now < last + threshhold) {
            // hold on to it
            clearTimeout(deferTimer);
            deferTimer = setTimeout(function() {
                last = now;
                fn.apply(context, args);
            }, threshhold);
        } else {
            last = now;
            fn.apply(context, args);
        }
    };
};

回答by Paolo

I use several HTML5 default sliders in the same page with the following setup:

我在同一页面中使用了几个 HTML5 默认滑块,设置如下:

  • Output tag in the page changes value when the slider is moved using the oninputevent
  • A changeevent is triggered once on release
  • 使用oninput事件移动滑块时,页面中的输出标记会更改值
  • 一个change事件被触发一次就发布

Tested with the latest Chrome and compiles well on a Raspberry with Node and Socket.io.

使用最新的 Chrome 进行测试,并在带有 Node 和 Socket.io 的 Raspberry 上编译良好。

<output id="APIDConKpVal"></output>&nbsp; <input type="range"
             class="PIDControlSlider"
             min="0"
             max="1500"
             step="1"
             id="APIDConKp"
             oninput="APIDConKpVal.value=value"/>

<output id="APIDConKiVal"></output>&nbsp; <input type="range"
             class="PIDControlSlider"
             min="0"
             max="2000"
             step="1"
             id="APIDConKi"
             oninput="APIDConKiVal.value=value"/>

A simple Javascript code creates the listeners. You might need to try different events instead of 'change' in the last line to see what fits you.

一个简单的 Javascript 代码创建监听器。您可能需要在最后一行尝试不同的事件而不是“更改”,以查看适合您的内容。

window.onload=function()
{
 var classname = document.getElementsByClassName("PIDControlSlider");

    var myFunction = function() {
        var attribute = this.getAttribute("id");
//Your code goes here
        socket.emit('SCMD', this.getAttribute("id")+' '+ this.value);
    };

    for(var i=0;i<classname.length;i++){
        classname[i].addEventListener('change', myFunction, false);
    }
}

回答by Scott

Here's what I use for capturing the 'change event' for the html5 range slider:

这是我用于捕获 html5 范围滑块的“更改事件”的内容:

HTML:

HTML:

<form oninput="output1.value=slider1.value">
    <input type="range" name="slider1" value="50"/>
    <output name="output1" for="slider1">50</output>
</form>

JavaScript:

JavaScript:

var $slider = $('input[name="slider1"]');

$slider.bind('change', function(e) {
    e.preventDefault();
    console.log($(this).val());
});

You can also bind the 'click' event to the range slider if you want to return its value when it has been clicked (or even dragged). Think of it like a 'mouseup' event. (I did try that but the slider didn't stop after I had clicked on the slider.)

如果您想在单击(甚至拖动)时返回其值,您还可以将 'click' 事件绑定到范围滑块。把它想象成一个“mouseup”事件。(我确实尝试过,但是在我单击滑块后滑块并没有停止。)

JavaScript:

JavaScript:

$slider.bind('click', function(e) {
    e.preventDefault();
    console.log($this).val());
}

On a side note, this returns a string so make sure you use 'parseInt($(this).value())' when appropriate.

附带说明一下,这会返回一个字符串,因此请确保在适当的时候使用 'parseInt($(this).value())'。

Hope this helps.

希望这可以帮助。

回答by alejandro

onchange works just fine , but I needed to update the value while sliding it.

onchange 工作得很好,但我需要在滑动时更新值。

var interval;
$("#rangeinput").mousedown(function(event){
    interval = setInterval(function(){
        $("#output").html($("#rangeinput").val());
        console.log("running");
    },150);
});

$("#rangeinput").mouseup(function(event){
    clearInterval(interval);
});

http://jsbin.com/vibuc/1/

http://jsbin.com/vibuc/1/

回答by Sagiv Ofek

another suggest:

另一个建议:

$(".slider").change(function(){    
  if (this.sliderTimeour) clearTimeout(this.sliderTimeour);
  this.sliderTimeour = setTimeout(function(){
    //your code here
  },delayTimeHere);
});