如何停止和播放jquery脚本

2024-02-27

我在用着slidesjs http://www.slidesjs.com/在单页网站上创建 5 个不同的幻灯片/画廊。它们都有“.slides”类并有自己的 ID。

在调用播放函数之前,我不希望播放任何幻灯片。我已经能够使用以下方法成功阻止每个幻灯片在加载时播放:

    function initiateSlides() {
    $('.slides').slides({
        generateNextPrev: true,
        fadeSpeed: 800,
        hoverPause: true,
        play: 3000,
        pause: 2500,
        preloadImage: 'images/loading.gif',
        effect: 'fade'
    });
    clearInterval($('#projects-commercial-slides').data('interval'));
    clearInterval($('#projects-residential-slides').data('interval'));
    clearInterval($('#projects-hospitality-slides').data('interval'));
    clearInterval($('#projects-public-slides').data('interval'));
    clearInterval($('#projects-industrial-slides').data('interval'));
}

(使用“.slides”类不会停止幻灯片放映,因此需要使用 ID。)但是,我现在无法播放任何幻灯片。我尝试过以下方法:

function playSlides() {
    $('#projects-residential-slides').animate();
}

function playSlides() {
    $('#projects-residential-slides').play();
}

function playSlides() {
    $('#projects-residential-slides').animate({
        animationStart:0
        });
}

function playSlides() {
    $('#projects-residential-slides').animate('next',fade);
}

我们将非常感激您的建议,因为我已经为此工作好几天了(!)。我很高兴我可能不会阻止幻灯片以最优雅的方式播放。完整的slides.jquery.js在这里:

    /*
* Slides, A Slideshow Plugin for jQuery
* Intructions: http://slidesjs.com
* By: Nathan Searles, http://nathansearles.com
* Version: 1.1.8
* Updated: June 1st, 2011
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function($){
    $.fn.slides = function( option ) {
        // override defaults with specified option
        option = $.extend( {}, $.fn.slides.option, option );

        return this.each(function(){
            // wrap slides in control container, make sure slides are block level
            $('.' + option.container, $(this)).children().wrapAll('<div class="slides_control"/>');

            var elem = $(this),
                control = $('.slides_control',elem),
                total = control.children().size(),
                width = control.children().outerWidth(),
                height = control.children().outerHeight(),
                start = option.start - 1,
                effect = option.effect.indexOf(',') < 0 ? option.effect : option.effect.replace(' ', '').split(',')[0],
                paginationEffect = option.effect.indexOf(',') < 0 ? effect : option.effect.replace(' ', '').split(',')[1],
                next = 0, prev = 0, number = 0, current = 0, loaded, active, clicked, position, direction, imageParent, pauseTimeout, playInterval;

            // animate slides
            function animate(direction, effect, clicked) {
                if (!active && loaded) {
                    active = true;
                    // start of animation
                    option.animationStart(current + 1);
                    switch(direction) {
                        case 'next':
                            // change current slide to previous
                            prev = current;
                            // get next from current + 1
                            next = current + 1;
                            // if last slide, set next to first slide
                            next = total === next ? 0 : next;
                            // set position of next slide to right of previous
                            position = width*2;
                            // distance to slide based on width of slides
                            direction = -width*2;
                            // store new current slide
                            current = next;
                        break;
                        case 'prev':
                            // change current slide to previous
                            prev = current;
                            // get next from current - 1
                            next = current - 1;
                            // if first slide, set next to last slide
                            next = next === -1 ? total-1 : next;                                
                            // set position of next slide to left of previous
                            position = 0;                               
                            // distance to slide based on width of slides
                            direction = 0;      
                            // store new current slide
                            current = next;
                        break;
                        case 'pagination':
                            // get next from pagination item clicked, convert to number
                            next = parseInt(clicked,10);
                            // get previous from pagination item with class of current
                            prev = $('.' + option.paginationClass + ' li.'+ option.currentClass +' a', elem).attr('href').match('[^#/]+$');
                            // if next is greater then previous set position of next slide to right of previous
                            if (next > prev) {
                                position = width*2;
                                direction = -width*2;
                            } else {
                            // if next is less then previous set position of next slide to left of previous
                                position = 0;
                                direction = 0;
                            }
                            // store new current slide
                            current = next;
                        break;
                    }

                    // fade animation
                    if (effect === 'fade') {
                        // fade animation with crossfade
                        if (option.crossfade) {
                            // put hidden next above current
                            control.children(':eq('+ next +')', elem).css({
                                zIndex: 10
                            // fade in next
                            }).fadeIn(option.fadeSpeed, option.fadeEasing, function(){
                                if (option.autoHeight) {
                                    // animate container to height of next
                                    control.animate({
                                        height: control.children(':eq('+ next +')', elem).outerHeight()
                                    }, option.autoHeightSpeed, function(){
                                        // hide previous
                                        control.children(':eq('+ prev +')', elem).css({
                                            display: 'none',
                                            zIndex: 0
                                        });                             
                                        // reset z index
                                        control.children(':eq('+ next +')', elem).css({
                                            zIndex: 0
                                        });                                 
                                        // end of animation
                                        option.animationComplete(next + 1);
                                        active = false;
                                    });
                                } else {
                                    // hide previous
                                    control.children(':eq('+ prev +')', elem).css({
                                        display: 'none',
                                        zIndex: 0
                                    });                                 
                                    // reset zindex
                                    control.children(':eq('+ next +')', elem).css({
                                        zIndex: 0
                                    });                                 
                                    // end of animation
                                    option.animationComplete(next + 1);
                                    active = false;
                                }
                            });
                        } else {
                            // fade animation with no crossfade
                            control.children(':eq('+ prev +')', elem).fadeOut(option.fadeSpeed,  option.fadeEasing, function(){
                                // animate to new height
                                if (option.autoHeight) {
                                    control.animate({
                                        // animate container to height of next
                                        height: control.children(':eq('+ next +')', elem).outerHeight()
                                    }, option.autoHeightSpeed,
                                    // fade in next slide
                                    function(){
                                        control.children(':eq('+ next +')', elem).fadeIn(option.fadeSpeed, option.fadeEasing);
                                    });
                                } else {
                                // if fixed height
                                    control.children(':eq('+ next +')', elem).fadeIn(option.fadeSpeed, option.fadeEasing, function(){
                                        // fix font rendering in ie, lame
                                        if($.browser.msie) {
                                            $(this).get(0).style.removeAttribute('filter');
                                        }
                                    });
                                }                                   
                                // end of animation
                                option.animationComplete(next + 1);
                                active = false;
                            });
                        }
                    // slide animation
                    } else {
                        // move next slide to right of previous
                        control.children(':eq('+ next +')').css({
                            left: position,
                            display: 'block'
                        });
                        // animate to new height
                        if (option.autoHeight) {
                            control.animate({
                                left: direction,
                                height: control.children(':eq('+ next +')').outerHeight()
                            },option.slideSpeed, option.slideEasing, function(){
                                control.css({
                                    left: -width
                                });
                                control.children(':eq('+ next +')').css({
                                    left: width,
                                    zIndex: 5
                                });
                                // reset previous slide
                                control.children(':eq('+ prev +')').css({
                                    left: width,
                                    display: 'none',
                                    zIndex: 0
                                });
                                // end of animation
                                option.animationComplete(next + 1);
                                active = false;
                            });
                            // if fixed height
                            } else {
                                // animate control
                                control.animate({
                                    left: direction
                                },option.slideSpeed, option.slideEasing, function(){
                                    // after animation reset control position
                                    control.css({
                                        left: -width
                                    });
                                    // reset and show next
                                    control.children(':eq('+ next +')').css({
                                        left: width,
                                        zIndex: 5
                                    });
                                    // reset previous slide
                                    control.children(':eq('+ prev +')').css({
                                        left: width,
                                        display: 'none',
                                        zIndex: 0
                                    });
                                    // end of animation
                                    option.animationComplete(next + 1);
                                    active = false;
                                });
                            }
                        }
                    // set current state for pagination
                    if (option.pagination) {
                        // remove current class from all
                        $('.'+ option.paginationClass +' li.' + option.currentClass, elem).removeClass(option.currentClass);
                        // add current class to next
                        $('.' + option.paginationClass + ' li:eq('+ next +')', elem).addClass(option.currentClass);
                    }
                }
            } // end animate function

            function stop() {
                // clear interval from stored id
                clearInterval(elem.data('interval'));
            }

            function pause() {
                if (option.pause) {
                    // clear timeout and interval
                    clearTimeout(elem.data('pause'));
                    clearInterval(elem.data('interval'));
                    // pause slide show for option.pause amount
                    pauseTimeout = setTimeout(function() {
                        // clear pause timeout
                        clearTimeout(elem.data('pause'));
                        // start play interval after pause
                        playInterval = setInterval( function(){
                            animate("next", effect);
                        },option.play);
                        // store play interval
                        elem.data('interval',playInterval);
                    },option.pause);
                    // store pause interval
                    elem.data('pause',pauseTimeout);
                } else {
                    // if no pause, just stop
                    stop();
                }
            }

            // 2 or more slides required
            if (total < 2) {
                return;
            }

            // error corection for start slide
            if (start < 0) {
                start = 0;
            }

            if (start > total) {
                start = total - 1;
            }

            // change current based on start option number
            if (option.start) {
                current = start;
            }

            // randomizes slide order
            if (option.randomize) {
                control.randomize();
            }

            // make sure overflow is hidden, width is set
            $('.' + option.container, elem).css({
                overflow: 'hidden',
                // fix for ie
                position: 'relative'
            });

            // set css for slides
            control.children().css({
                position: 'absolute',
                top: 0, 
                left: control.children().outerWidth(),
                zIndex: 0,
                display: 'none'
             });

            // set css for control div
            control.css({
                position: 'relative',
                // size of control 3 x slide width
                width: (width * 3),
                // set height to slide height
                height: height,
                // center control to slide
                left: -width
            });

            // show slides
            $('.' + option.container, elem).css({
                display: 'block'
            });

            // if autoHeight true, get and set height of first slide
            if (option.autoHeight) {
                control.children().css({
                    height: 'auto'
                });
                control.animate({
                    height: control.children(':eq('+ start +')').outerHeight()
                },option.autoHeightSpeed);
            }

            // checks if image is loaded
            if (option.preload && control.find('img:eq(' + start + ')').length) {
                // adds preload image
                $('.' + option.container, elem).css({
                    background: 'url(' + option.preloadImage + ') no-repeat 50% 50%'
                });

                // gets image src, with cache buster
                var img = control.find('img:eq(' + start + ')').attr('src') + '?' + (new Date()).getTime();

                // check if the image has a parent
                if ($('img', elem).parent().attr('class') != 'slides_control') {
                    // If image has parent, get tag name
                    imageParent = control.children(':eq(0)')[0].tagName.toLowerCase();
                } else {
                    // Image doesn't have parent, use image tag name
                    imageParent = control.find('img:eq(' + start + ')');
                }

                // checks if image is loaded
                control.find('img:eq(' + start + ')').attr('src', img).load(function() {
                    // once image is fully loaded, fade in
                    control.find(imageParent + ':eq(' + start + ')').fadeIn(option.fadeSpeed, option.fadeEasing, function(){
                        $(this).css({
                            zIndex: 5
                        });
                        // removes preload image
                        $('.' + option.container, elem).css({
                            background: ''
                        });
                        // let the script know everything is loaded
                        loaded = true;
                        // call the loaded funciton
                        option.slidesLoaded();
                    });
                });
            } else {
                // if no preloader fade in start slide
                control.children(':eq(' + start + ')').fadeIn(option.fadeSpeed, option.fadeEasing, function(){
                    // let the script know everything is loaded
                    loaded = true;
                    // call the loaded funciton
                    option.slidesLoaded();
                });
            }

            // click slide for next
            if (option.bigTarget) {
                // set cursor to pointer
                control.children().css({
                    cursor: 'pointer'
                });
                // click handler
                control.children().click(function(){
                    // animate to next on slide click
                    animate('next', effect);
                    return false;
                });                                 
            }

            // pause on mouseover
            if (option.hoverPause && option.play) {
                control.bind('mouseover',function(){
                    // on mouse over stop
                    stop();
                });
                control.bind('mouseleave',function(){
                    // on mouse leave start pause timeout
                    pause();
                });
            }

            // generate next/prev buttons
            if (option.generateNextPrev) {
                $('.' + option.container, elem).after('<a href="#" class="'+ option.prev +'">Prev</a>');
                $('.' + option.prev, elem).after('<a href="#" class="'+ option.next +'">Next</a>');
            }

            // next button
            $('.' + option.next ,elem).click(function(e){
                e.preventDefault();
                if (option.play) {
                    pause();
                }
                animate('next', effect);
            });

            // previous button
            $('.' + option.prev, elem).click(function(e){
                e.preventDefault();
                if (option.play) {
                     pause();
                }
                animate('prev', effect);
            });

            // generate pagination
            if (option.generatePagination) {
                // create unordered list
                if (option.prependPagination) {
                    elem.prepend('<ul class='+ option.paginationClass +'></ul>');
                } else {
                    elem.append('<ul class='+ option.paginationClass +'></ul>');
                }
                // for each slide create a list item and link
                control.children().each(function(){
                    $('.' + option.paginationClass, elem).append('<li><a href="#'+ number +'">'+ (number+1) +'</a></li>');
                    number++;
                });
            } else {
                // if pagination exists, add href w/ value of item number to links
                $('.' + option.paginationClass + ' li a', elem).each(function(){
                    $(this).attr('href', '#' + number);
                    number++;
                });
            }

            // add current class to start slide pagination
            $('.' + option.paginationClass + ' li:eq('+ start +')', elem).addClass(option.currentClass);

            // click handling 
            $('.' + option.paginationClass + ' li a', elem ).click(function(){
                // pause slideshow
                if (option.play) {
                     pause();
                }
                // get clicked, pass to animate function                    
                clicked = $(this).attr('href').match('[^#/]+$');
                // if current slide equals clicked, don't do anything
                if (current != clicked) {
                    animate('pagination', paginationEffect, clicked);
                }
                return false;
            });

            // click handling 
            $('a.link', elem).click(function(){
                // pause slideshow
                if (option.play) {
                     pause();
                }
                // get clicked, pass to animate function                    
                clicked = $(this).attr('href').match('[^#/]+$') - 1;
                // if current slide equals clicked, don't do anything
                if (current != clicked) {
                    animate('pagination', paginationEffect, clicked);
                }
                return false;
            });

            if (option.play) {
                // set interval
                playInterval = setInterval(function() {
                    animate('next', effect);
                }, option.play);
                // store interval id
                elem.data('interval',playInterval);
            }
        });
    };

    // default options
    $.fn.slides.option = {
        preload: false, // boolean, Set true to preload images in an image based slideshow
        preloadImage: '/img/loading.gif', // string, Name and location of loading image for preloader. Default is "/img/loading.gif"
        container: 'slides_container', // string, Class name for slides container. Default is "slides_container"
        generateNextPrev: false, // boolean, Auto generate next/prev buttons
        next: 'next', // string, Class name for next button
        prev: 'prev', // string, Class name for previous button
        pagination: true, // boolean, If you're not using pagination you can set to false, but don't have to
        generatePagination: true, // boolean, Auto generate pagination
        prependPagination: false, // boolean, prepend pagination
        paginationClass: 'pagination', // string, Class name for pagination
        currentClass: 'current', // string, Class name for current class
        fadeSpeed: 350, // number, Set the speed of the fading animation in milliseconds
        fadeEasing: '', // string, must load jQuery's easing plugin before http://gsgd.co.uk/sandbox/jquery/easing/
        slideSpeed: 350, // number, Set the speed of the sliding animation in milliseconds
        slideEasing: '', // string, must load jQuery's easing plugin before http://gsgd.co.uk/sandbox/jquery/easing/
        start: 1, // number, Set the speed of the sliding animation in milliseconds
        effect: 'slide', // string, '[next/prev], [pagination]', e.g. 'slide, fade' or simply 'fade' for both
        crossfade: false, // boolean, Crossfade images in a image based slideshow
        randomize: false, // boolean, Set to true to randomize slides
        play: 0, // number, Autoplay slideshow, a positive number will set to true and be the time between slide animation in milliseconds
        pause: 0, // number, Pause slideshow on click of next/prev or pagination. A positive number will set to true and be the time of pause in milliseconds
        hoverPause: false, // boolean, Set to true and hovering over slideshow will pause it
        autoHeight: false, // boolean, Set to true to auto adjust height
        autoHeightSpeed: 350, // number, Set auto height animation time in milliseconds
        bigTarget: false, // boolean, Set to true and the whole slide will link to next slide on click
        animationStart: function(){}, // Function called at the start of animation
        animationComplete: function(){}, // Function called at the completion of animation
        slidesLoaded: function() {} // Function is called when slides is fully loaded
    };

    // Randomize slide order on load
    $.fn.randomize = function(callback) {
        function randomizeOrder() { return(Math.round(Math.random())-0.5); }
            return($(this).each(function() {
            var $this = $(this);
            var $children = $this.children();
            var childCount = $children.length;
            if (childCount > 1) {
                $children.hide();
                var indices = [];
                for (i=0;i<childCount;i++) { indices[indices.length] = i; }
                indices = indices.sort(randomizeOrder);
                $.each(indices,function(j,k) { 
                    var $child = $children.eq(k);
                    var $clone = $child.clone(true);
                    $clone.show().appendTo($this);
                    if (callback !== undefined) {
                        callback($child, $clone);
                    }
                $child.remove();
            });
            }
        }));
    };
})(jQuery);

我建议使用(或看看)Slidejs 2https://github.com/nathansearles/Slides https://github.com/nathansearles/Slides.

您尝试的所有方法都不起作用的原因是因为他从未公开您尝试调用的那些方法(有些方法甚至不存在)。调用不带播放选项的幻灯片将阻止自动播放,但它也会初始化幻灯片js(包装容器的子级)。稍后再次调用它会重新初始化它,从而导致您提到的双重包装。

在版本 2 中,他添加了一个适合您的 API:

// With slidejs2
// stopping all slides
$(".slides").each(function() { $(this).slides("stop"); });
// playing all slides
$(".slides").each(function() { $(this).slides("play"); });

除此之外,您的clearInterval代码也可以写成:

$('.slides').each(function() { clearInterval($(this).data("interval")); });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何停止和播放jquery脚本 的相关文章

随机推荐

  • 如何在NodeJS中获取UTC日期对象? [复制]

    这个问题在这里已经有答案了 我想获取 UTC 中的当前日期对象 我尝试使用new Date Date now 等等 但他们返回当地时间 如何获取 UTC 日期对象 我想要 Date 对象 而不是字符串表示形式 只需使用new Date ne
  • Jetpack Compose dev06 setContent() 不起作用?

    更新到 dev06 并运行应用程序时 出现以下错误 java lang NoSuchMethodError No static method setContent Landroid app Activity Lkotlin jvm func
  • Android Spinner:获取所选项目更改事件

    当所选项目发生更改时 如何设置 Spinner 的事件侦听器 基本上我想做的事情与此类似 spinner1 onSelectionChange handleSelectionChange void handleSelectionChange
  • 如何在 Ubuntu 上的 NetBeans 中设置 zend 自动完成

    我在 Ubuntu 11 04 上的 NetBeans 7 1 中设置 Zend 自动完成代码时陷入困境 一点帮助就太好了 我在工具 gt 选项 gt PHP gt Zend中设置 usr bin zf sh 作为 Zend 脚本 按下 注
  • 返回引用与返回值 C++ 之间的区别

    关于为什么有必要从函数返回引用的问题 如果我们替换以下代码 其行为完全相同int with int在第 9 行和第 16 行 在我的示例代码中 返回引用与值并不重要吗 在什么样的例子中它会开始变得重要 在我看来 我们无法返回函数局部变量的引
  • 禁用 iframe 自动调整大小

    我正在使用一个包含 iframe 的网页 iframe 中包含大量数据 每次加载时 其高度都会扩展到其中内容的范围 然而 这使我的页面消失了 是否有办法锁定 iframe 的高度并允许用户滚动浏览内容 嗯 奇怪 你有这个问题的示例链接吗 当
  • 在 OS X 上的 Java swing 中设置默认应用程序图标图像

    我正在尝试设置 Jar 文件的图标图像 setIconImage new ImageIcon getClass getResource logo png getImage 在 Mac OS X 10 7 4 中运行时 出现以下错误 Jun
  • Jenkins 管道:如何触发另一个作业并等待它而不使用额外的代理/执行器

    我正在尝试设置各种 Jenkins 管道 其最后阶段始终是运行一些验收测试 长话短说 所有产品的验收测试和测试数据 其中大部分是共享的 都被签入同一个存储库 大小约为 0 5 GB 因此 似乎最好为验收测试提供一个单独的工作 并通过每个管道
  • 铁路路线:具有约束的控制器命名空间(子域)

    目的是创建一个子域来容纳所有管理功能 CRUD 子域的名称是 admin 负责的控制器集也组织在 的命名空间下admin 即控制器位于应用程序 控制器 管理目录 理想情况下 应该有以下路线 admin mydomain com produc
  • 如何在文本视图的左上角设置可绘制对象?

  • 对数据表中的筛选列求和

    我正在尝试对数据表中过滤列的结果求和 我查看了他们网站上提出的问题 人们已经成功使用这个方法 http datatables net forums discussion 2053 fnfootercallback sum column af
  • 如何比较 string.characterAtIndex 和字母?

    我使用 swift 我想做的是检查这一点 if string characterAtIndex i a 但我收到错误 如何转换这个 a 以便它可以与我循环的字符类型相同 Thanks 你需要转变你UniChar characterAtInd
  • PhoneGap/Cordova 以及最新版本的 Google Chrome 中没有“Access-Control-Allow-Origin”

    我工作于Sencha Touch Framework跨移动平台 我正在运行我的项目mac os x localhost 我试图通过请求获取服务器的响应Ext Ajax request 我收到一个典型错误CORS XMLHttpRequest
  • 在 C/C++ 中初始化大小未知的数组 [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 如何在 C 中初始化数组 例如 void initArr int size C语言没有提供初始化数组的选项 如果他的大小不是一个常量值 并
  • 如何判断CSS是否已经加载?

    我如何断言页面的 CSS 已在 Watin 2 1 中成功加载并应用其样式 在做了一些研究并写下我的答案之后 我偶然发现这个链接 http www phpied com when is a stylesheet really loaded
  • iOS 5 中的离屏 UITextView 不可见/清晰文本

    我有一个从笔尖加载的离屏 UITextView 实例 当用户点击 评论 按钮时 该实例会移动到屏幕框架中 输入使用的任何文本都是不可见的 如果用户旋转设备 则会显示文本 我尝试过抛出 setNeedsDisplay 和 setNeedsLa
  • ffmpeg的UDP协议是什么?

    ffmpeg的UDP协议是什么 这是另一个例子question https stackoverflow com questions 12003014 pipe udp input to ffmpeg ffmpeg i udp localho
  • 我们可以检查一个指针以确保它是一个有效的地址吗?

    我的想法是打印它指向的对象 我认为一个有效的指针应该有一个有效的对象 如果我们尝试打印出对象 我们会验证指针是否有效 我对吗 我认为一个有效的指针应该有一个有效的对象 是的 这就是有效指针的定义 如果我们尝试打印出对象 我们会验证指针是否有
  • setInterval 不适用于 ajax 调用

    我对网络服务进行了 getJson 调用并且工作正常 现在我尝试每 10 秒发出一次请求 使用带有回调函数的 setInterval 来触发弹出警报 我无法让它发挥作用 这是代码 function ajxCall getJSON http
  • 如何停止和播放jquery脚本

    我在用着slidesjs http www slidesjs com 在单页网站上创建 5 个不同的幻灯片 画廊 它们都有 slides 类并有自己的 ID 在调用播放函数之前 我不希望播放任何幻灯片 我已经能够使用以下方法成功阻止每个幻灯