简体   繁体   English

jQuery UI Slider用于通过自动滑动更改图像

[英]jQuery UI Slider for changing Image with auto slide

I´d like to build a UI Slider to change an Image. 我想构建一个UI滑块来更改图像。 So far, I´ve managed that the Image will change manually and automaticly every three Seconds. 到目前为止,我已经设法使图像每三秒钟手动和自动更改一次。
I´m not very happy with the code, because when it reaches the max-value and repeats from beginning, it skippes the last value because of the setInterval. 我对代码不是很满意,因为当它达到最大值并从头开始重复时,由于setInterval,它将跳过最后一个值。 Is there an easier and prettier way to solve this? 有没有更简单,更漂亮的方法来解决这个问题?

HTML 的HTML

<div id="wrapper">
    <div class="image">
        <img id="image" src="http://fakeimg.pl/350x200/?text=0&font=lobster" />
    </div>
    <div id="slider"></div>
</div>

Script 脚本

$(function () {
    $('#slider').slider({
        value: 0,
        min: 0,
        max: 5,
        step: 1,
        change: function (event, ui) {
            var slideruivalue = (ui.value);
            image = $('#image');
            image.attr('src', 'http://fakeimg.pl/350x200/?text=' + slideruivalue);

            if (slideruivalue == $(this).data("slider").options.max) {
                $('#slider').slider('value', 0);
            }
        }
    });

    $(function AutoSlider() {
        setTimeout(function () {
            $("#slider").slider("value", $('#slider').slider("value") + 1);
        }, 3000);
        setTimeout(AutoSlider, 3000);
    });
});

jsFiddle Example jsFiddle示例

In your setTimeout, get the max of your slider, and then calculate the new value with a modulus (operator %) on max+1 : 在setTimeout中,获取滑块的最大值,然后使用max + 1上的模数(运算符%)计算新值:

    setInterval(function () {
        var value = $('#slider').slider("value");
        var max = $('#slider').slider( "option", "max" );
        $("#slider").slider("value", (value + 1)% (max+1));
    }, 3000);

Then, there is no need to check the value in the change callback :) 然后,无需检查更改回调中的值:)

You can also use setInterval instead of two setTimeout 您也可以使用setInterval而不是两个setTimeout

http://jsfiddle.net/q5R68/1/ http://jsfiddle.net/q5R68/1/

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

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