Animating slider handle when altering the jQuery U

2020-07-18 08:26发布

问题:

I'm using the jQuery UI (1.8) slider widget to enable the user to slide/scroll a series of icons horizontally. Sometimes I want to move the slider programatically and the correct way to do that is by altering the option "value", like this:

$("#content-slider").slider("option", "value", 37);

The motion of the slider handle is instant though. I'd like the motion to be animated. This can be done on a lower level, by animating the "left" CSS property of the handle, like this:

$(".ui-slider-handle").animate({ left: position, easing: 'swing' }, 450);

...but if I do this, I just set the left property of the CSS for the handle. The actual value of the slider is not affected. So I thought of adding a callback at the end of the animation where the value is set, something like this:

$(".ui-slider-handle").animate({ left: position, easing: 'swing' }, 450, function() {
    // Callback - set the new slider value
    $("#content-slider").slider("option", "value", position);
});

When I try the code above (with the callback) I get a jQuery error about too much recursion, so I think that this is not a good way to accomplish what I want (ugly code).

Is there a better way to animate the slider handle when the value of the slider is altered programatically?

Thanks in advance! /Thomas Kahn

回答1:

You simply enable the animate option on the slider to accomplish this. From the documentation:

Whether to slide handle smoothly when user click outside handle on the bar. Will also accept a string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).

Therefore your code will look something like this:

$("#content-slider").slider({
    animate: true
});

Here's a live demo of this: http://www.jsfiddle.net/VVHGx/


I think I know what you're doing wrong - you need to change the value of the slider via the .slider('value') method instead of the .slider('option', 'value)` method:

$('#content-slider').slider('value', 42);


回答2:

In case you are trying to do this with a range slider:

var slider = $("#slider").slider({
    animate: true,
    range : true,
    values: [10,40]
});

$('#move').click(function(){
    slider.slider('values', [0,60]);
    return false;
});
  • forked fiddle​