jQuery-ui slider animation when setting value programmatically

落爺英雄遲暮 提交于 2020-02-04 05:44:07

问题


I'm using a jQuery-ui slider and some buttons for a quick selection of a little set of values.

When the user clicks one of these buttons, the slider is set to the corresponding value through the .slider method:

$("#mySlider").slider("value", myValue);

This works fine, but I'd like to see the sliding animation. I tried with

$("#mySlider").slider({value:myValue, animate:true})

but it doesn't work as expected, since the animation is only enabled when, later, the user clicks on the slider bar.

Should I write a function using setTimeout to achieve what I want or is there a higher-level way to do this with jQuery?


回答1:


Here is a jsfiddle illustrating a solution: http://jsfiddle.net/exXLV/8/

The Trick seems to be to create a slider and set it's animate option to true, slow ,etc. and after that you should set the value of the slider via $("#slider").slider('value', 150);

Notice the difference between using the .slider('value', 150) syntax ("the value" function) and using the .slider({value:myValue, animate:true}) syntax ("the option" function).

HTML:

<h1>HTML Slider Test</h1>

<div id="slider"></div>

<p>Your slider has a value of <span id="slider-value"></span></p>

<button type="button">Set to 150</button>

JS:

$("#slider").slider(
{
            value:100,
            min: 0,
            max: 500,
            step: 1,
            animate: "slow",
            slide: function( event, ui ) {
                $( "#slider-value" ).html( ui.value );
            }
}
);

$( "#slider-value" ).html(  $('#slider').slider('value') );


$("button").click( function(){
    $("#slider").slider('value', 150);
});



回答2:


Use animate along with value method

Something like this should do

var slider = $(".slider").slider({
    value: 50,
    animate: true
});

$('#animate').click(function(){
    slider.slider('value', //required value);
});

DEMO

Hope this helps



来源:https://stackoverflow.com/questions/10608314/jquery-ui-slider-animation-when-setting-value-programmatically

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