Live output in jQuery HTML5 range slider

这一生的挚爱 提交于 2019-12-06 03:59:08

问题


I'm trying to get a live output from a HTML5 input range slider into a javascript variable. Right now, I'm using <input type="range" id="rangevalue" onchange="arduino()">

The way I have it working is doing what I want, but it's not "live." I want to have it so while you're dragging the slider, it updates the variable, and not only once you let go. For example: when I'm dragging the slider from 1 to 5, I want the variable to update while I'm dragging, so it will update with 1,2,3,4,5 and not only jump from 1 to 5 once I release the slider.

Is it possible to do such a thing? Any recommendations? I was using the jQuery slider plugin, but it was not touch compatible, which eliminated its purpose.

Thanks for all help in advance!

EDIT - I must not have explained well enough, I know how to get the value of a range slider, I just want to get a "live" output from it.


回答1:


$("#rangevalue").mousemove(function () {
    $("#text").text($("#rangevalue").val())
})

jsFiddle example

Or in plain JS:

var inp = document.getElementById('rangevalue');
inp.addEventListener("mousemove", function () {
    document.getElementById('text').innerHTML = this.value;
});



回答2:


Yes it is possible. What we need to do is use .mousedown() and .mouseup() with a Boolean value to keep track that we are holding down the mouse mousedown. When the mouse is held down set mousedown to true and use a setTimeout that keeps updating the value. This way while you are dragging slider the value is being constantly updated. For example:

HTML

<label id="text">0</label>
<input type="range" value=0 min=0 max=10 id="rangevalue">

JavaScript

var mouseDown = false

$("#rangevalue").mousedown(function() {
   mouseDown = true;
    updateSlider()
});

$("#rangevalue").mouseup(function() {
    mouseDown = false;
});

function updateSlider() {
    if(mouseDown) {
        // Update the value while the mouse is held down.
        $("#text").text($("#rangevalue").val());
        setTimeout(updateSlider, 50); 
    }
}

Here is a fiddle




回答3:


You could also use the oninput attribute.

    <input type="range" min="5" max="10" step="1" 
   oninput="arduino()" onchange="arduino()">

More Information on Bugzilla




回答4:


I think it is working with your Code.

<input type="range" id="rangevalue" onchange="arduino()">
<p id="t"></p>
    <script>
        function arduino() {
    document.getElementById("t").innerHTML = document.getElementById("rangevalue").value;
}</script>

JSFiddle



来源:https://stackoverflow.com/questions/26429492/live-output-in-jquery-html5-range-slider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!