如何停止和玩jQuery脚本 [英] How to stop and play jquery script

查看:76
本文介绍了如何停止和玩jQuery脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用幻灯片在单页网站上创建5个不同的幻灯片/画廊。他们都有'.slides'类,并有自己的ID。



我不希望任何幻灯片播放,直到播放函数被调用。我已经能够成功阻止每个幻灯片放映使用以下内容进行播放:

 函数initiateSlides(){
$('。slides')。幻灯片({
generateNextPrev:true,
fadeSpeed:800,
hoverPause:true,
play:3000,
pause:2500 ,
preloadImage:'images / loading.gif',
效果:'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'));
}

(使用class'.slides'不会停止幻灯片显示,因此使用ID )但是,我现在无法播放任何幻灯片。我尝试了以下方法:

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


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

函数playSlides(){
$('#projects-residential-slides')。animate({
animationStart:0
}) ;


函数playSlides(){
$('#projects-residential-slides')。animate('next',fade);
}

您的建议会非常感谢,因为我一直在为此工作现在(!)。我很欣赏我可能不会阻止以最优雅的方式播放幻灯片。完整的幻灯片插件jQuery
* Intructions:http://slidesjs.com
*作者:Nathan Searles,http://nathansearles.com
*版本:1.1.8
*更新日期:2011年6月1日
*
*根据Apache许可证2.0版许可(许可证);
*除遵守许可证外,您不得使用此文件。
*您可以在
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*中获得许可证副本除非根据适用法律要求或书面同意,根据许可分配的软件
*以原样基础,
*分发,不附有任何明示或暗示的保证或条件。
*请参阅许可证以了解许可证下特定语言的管理权限和
*限制。
* /
(函数($){
$ .fn.slides =函数(选项){
//用指定选项覆盖默认值
option = $。 extend({},$ .fn.slides.option,option);

return this.each(function(){
//在控件容器中包装幻灯片,确保幻灯片是阻止的('。'+ 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 ,点击,位置,方向,imageParent,pauseTimeout,playInterval;

$ animate幻灯片
函数animate(方向,效果,点击){
if(!active&& loaded){
active = true;
//开始动画
option.animationStart(current + 1);
switch(direction){
case'next':
//将当前幻灯片更改为上一个
prev = current;
//从当前获得下一个+1
next = current + 1;
//如果上一张幻灯片放在第一张幻灯片旁边
next = total === next? 0:下一个;
//将下一张幻灯片的位置设置在前面
位置=宽度* 2;
//基于幻灯片宽度的幻灯片距离
direction = -width * 2;
//存储新的当前幻灯片
current = next;
休息;
case'prev':
//将当前幻灯片更改为上一个
prev = current;
//从当前获得下一个 - 1
next = current - 1;
//如果第一张幻灯片放在最后一张幻灯片的旁边
next = next === -1?总共1:下一个;
//将下一张幻灯片的位置设置在前面
位置= 0的左边;
//基于幻灯片宽度的幻灯片距离
direction = 0;
//存储新的当前幻灯片
current = next;
休息;
case'pagination':
//从分页项目点击下一页,转换为数字
next = parseInt(点击,10);
//从分页项获得前一分类的当前
prev = $('。'+ option.paginationClass +'li。'+ option.currentClass +'a',elem).attr(' href '属性)匹配('[^#/] + $');
//如果下一个大于上一个下一个幻灯片的前一个设置位置,则前一个
if(next> prev){
position = width * 2;
direction = -width * 2;
} else {
//如果next小于前一个
position = 0左边的下一个幻灯片的设置位置;
direction = 0;
}
//存储新的当前幻灯片
current = next;
休息;


//淡入淡出动画
if(effect ==='fade'){
//淡入淡出动画
if(option。 crossfade){
// //将隐藏的下一个当前
control.children(':eq('+ next +')',elem).css({
zIndex:10
)淡入
))。fadeIn(option.fadeSpeed,option.fadeEasing,function(){
if(option.autoHeight){
//将容器移动到下一个高度
control.animate({
height:control.children(':eq('+ next +')',elem).outerHeight()
},option.autoHeightSpeed,function() {
//隐藏之前的
control.children(':eq('+ prev +')',elem).css({
display:'none',
zIndex:0
});
// reset z index
control.children(':eq('+ next +')',elem).css({
zIndex:0
});
//动画结束
option.animationComplete(next + 1);
active = false;
});
} else {
//隐藏前面的
control.children(':eq('+ prev +')',elem).css({
display:'none' ,
zIndex:0
});
// reset zindex
control.children(':eq('+ next +')',elem).css({
zIndex:0
});
//动画结束
option.animationComplete(next + 1);
active = false;
}
});
} else {
//淡入淡出动画不带交叉淡化
control.children(':eq('+ prev +')',elem).fadeOut(option.fadeSpeed,option.fadeEasing ,function(){
//动画到新高度
if(option.autoHeight){
control.animate({
//将容器移动到下一个$ b $的高度b高度:control.children(':eq('+ next +')',elem).outerHeight()
},option.autoHeightSpeed,
//淡入幻灯片
函数(){
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 (){
//修正ie中的字体渲染,蹩脚
if($。browser.msie){
$(this).get(0).style.removeAttribute('filter' );
}
});
}
//动画结束
option.animationComplete(next + 1);
active = false;
});
}
//幻灯片动画
} else {
//向下移动到前一个
的右侧control.children(':eq('+ next +' )')。css({
left:position,
display:'block'
});
//动画到新高度
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
} );
//重置上一张幻灯片
control.children(':eq('+ prev +')')。css({
left:width,
display:'none',
zIndex:0
});
//动画结束
option.animationComplete(next + 1);
active = false;
});
//如果固定高度
} else {
//动画控件
control.animate({
left:direction
},option.slideSpeed, option.slideEasing,function(){
//动画重置后的控制位置
control.css({
left:-width
});
// reset并显示下一个
control.children(':eq('+ next +')')。css({
left:width,
zIndex:5
});
//重置上一张幻灯片
control.children(':eq('+ prev +')')。css({
left:width,
display:'none',
zIndex:0
} );
//动画结束
option.animationComplete(next + 1);
active = false;
});


//设置分页的当前状态
if(option.pagination){
//从当前类中删除所有
$(' 。'+ option.paginationClass +'li。'+ option.currentClass,elem).removeClass(option.currentClass);
//将当前类添加到下一个
$('。'+ option.paginationClass +'li:eq('+ next +')',elem).addClass(option.currentClass);
}

} //结束动画函数

函数stop(){
//从存储的id清除间隔
clearInterval elem.data( '间隔'));
}

函数暂停(){
if(option.pause){
//清除超时和间隔
clearTimeout(elem.data('暂停'));
clearInterval(elem.data('interval'));
//暂停幻灯片显示为option.pause amount
pauseTimeout = setTimeout(function(){
//清除暂停超时
clearTimeout(elem.data('pause')) ;
//暂停后开始播放间隔
playInterval = setInterval(function(){
animate(next,effect);
},option.play);
//存储播放间隔
elem.data('interval',playInterval);
},option.pause);
//存储暂停时间间隔
elem.data('pause',pauseTimeout);
} else {
//如果不停顿,只需停止
stop();



//需要2张或更多幻灯片
if(total <2){
return;


//开始幻灯片的错误核对
if(start< 0){
start = 0;
}

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


//根据开始选项编号改变当前值
if(option.start){
current = start;


//随机化幻灯片顺序
if(option.randomize){
control.randomize();
}

//确保溢出隐藏,宽度设置为
$('。'+ option.container,elem).css({
overflow: 'hidden',
//修正ie
的位置:'relative'
});

//为幻灯片设置css
control.children().css({
position:'absolute',
top:0,
:control.children()。outerWidth(),
zIndex:0,
display:'none'
});

//为控件div设置css
control.css({
位置:'relative',
//控件大小3 x幻灯片宽度
宽度:(宽* 3),
//设置高度以滑动高度
高度:高度,
//中心控制滑动
左:宽度
});
$ b $ //幻灯片
$('。'+ 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);
}

//检查图像是否被加载
if(option.preload&& control.find('img:eq('+ start +')') .length){
//添加预加载图片
$('。'+ option.container,elem).css({
background:'url('+ option.preloadImage +')不重复50%50%'
});

//获取映像src,并使用缓存触发器
var img = control.find('img:eq('+ start +')')。attr('src')+' ?'+(new Date())。getTime();

//检查图像是否有父元素
if($('img',elem).parent()。attr('class')!='slides_control'){
//如果图像具有父级,请获取标记名称
imageParent = control.children(':eq(0)')[0] .tagName.toLowerCase();
} else {
//图像没有父级,使用图像标签名称
imageParent = control.find('img:eq('+ start +')');


检查图像是否加载
control.find('img:eq('+ start +')')。attr('src',img) .load(function(){
//一旦图像完全加载,淡入
control.find(imageParent +':eq('+ start +')')。fadeIn(option.fadeSpeed, option.fadeEasing,function(){
$(this).css({
zIndex:5
});
//删除预加载图片
$(' 。'+ option.container,elem).css({
background:''
});
//让脚本知道所有内容都已加载
loaded = true;
//调用加载函数
option.slidesLoaded();
});
});
} else {
//如果没有预加载器在开始幻灯片中淡入
control.children(':eq('+ start +')')。fadeIn(option.fadeSpeed,option.fadeEasing ,函数(){
//让脚本知道所有的东西都被加载了
loaded = true;
//调用加载的函数
option.slidesLoaded();
});


//点击幻灯片下一个
if(option.bigTarget){
//将光标设置为指针
control.children()。 css({
cursor:'pointer'
});
//点击处理程序
control.children()。click(function(){
//在幻灯片上动画到下一个点击
animate('next',effect);
返回false;
});


//在鼠标悬停时暂停
if(option.hoverPause&& option.play){
control.bind('mouseover',function( ){
//在鼠标悬停处
stop();
});
control.bind('mouseleave',function(){
//在鼠标离开时开始暂停超时
pause();
});
}

//产生next / prev按钮
if(option.generateNextPrev){
$('。'+ option.container,elem).after( '< a href =#class ='+ option.prev +'>上一个< / a>'); $('。'+ option.prev,elem).after('< a href =#class ='+ option.next +'> Next< / a>');

$ b $ //下一个按钮
$('。'+ option.next,elem).click(function(e){
e.preventDefault() ;
if(option.play){
pause();
}
animate('next',effect);
});
$ b $ //上一个按钮
$('。'+ option.prev,elem).click(function(e){
e.preventDefault();
if(option.play){
pause();
}
animate('prev',effect);
});

//生成分页
if(option.generatePagination){
//创建无序列表
if(option.prependPagination){
elem.prepend ('< ul class ='+ option.paginationClass +'>< / ul>');
} else {
elem.append('< ul class ='+ option.paginationClass +'>< / ul>');
}
//为每张幻灯片创建一个列表项并链接
control.children()。each(function(){
$('。'+ option.paginationClass, );< / h>'< / li> .append('< li>< a href =#'+ number +'>'+(number + 1)+'< / a>< / li>');
number ++;
});
} else {
//如果分页存在,则将项目编号的href值添加到链接
$('。'+ option.paginationClass +'li a',elem).each (function(){
$(this).attr('href','#'+ number);
number ++;
});
}

//添加当前类开始幻灯片分页
$('。'+ option.paginationClass +'li:eq('+ start +')',elem ).addClass(option.currentClass);

//点击处理
$('。'+ option.paginationClass +'li a',elem).click(function(){
//暂停幻灯片
if(option.play){
pause();
}
//获得点击,传递给动画函数
clicked = $(this).attr('href ').match('[^#/] + $');
//如果当前幻灯片等于点击,不要做任何事
if(current!= clicked){
animate ('pagination',paginationEffect,clicked);
}
return false;
});
$ b $ //点击处理
$('a.link',elem).click(function(){
//暂停幻灯片
if(option.play ){
pause();
}
//获得点击,传递给动画函数
clicked = $(this).attr('href')。match(' ^#/] + $') - 1;
//如果当前幻灯片等于点击,不要做任何事
if(current!= clicked){
animate('pagination', paginationEffect,clicked);
}
return false;
});

if(option.play){
// set interval
playInterval = setInterval(function(){
animate('next',effect);
},option.play);
//存储间隔ID
elem.data('interval',playInterval);
}
});
};

//默认选项
$ .fn.slides.option = {
preload:false,//布尔型,将true设置为预加载图像中的图像幻灯片
preloadImage:'/img/loading.gif',//字符串,加载预加载器的图像的名称和位置。默认是/img/loading.gif
容器:'slides_container',// string,幻灯片容器的类名。默认为slides_container
generateNextPrev:false,//布尔型,自动生成next / prev按钮
next:'next',// string,下一个按钮的类名称
prev:'prev ',// string,前一个按钮的类名
分页:true,//布尔值,如果你没有使用分页,你可以设置为false,但不必
generatePagination:true, // boolean,自动生成分页
prependPagination:false,//布尔,前置分页
paginationClass:'pagination',//字符串,分页名称
currentClass:'current',/ / string,当前类的类名
fadeSpeed:350,//数字,以毫秒为单位设置淡入淡出动画的速度
fadeEasing:'',// string,必须在http://之前加载jQuery的easing插件。 //gsgd.co.uk/sandbox/jquery/easing/
slideSpeed:350,//数字,以毫秒为单位设置滑动动画的速度s
slideEasing:'',// string,必须在http://gsgd.co.uk/sandbox/jasing/easing/
start之前加载jQuery的easing插件:1,//数字,设置以毫秒为单位的滑动动画的速度
效果:'slide',//字符串,'[next / prev],[pagination]',例如'幻灯片,淡入淡出'或简单'淡入淡出'
crossfade:false,//布尔型,在基于图像的幻灯片中交叉淡入淡出图像
randomize:false,//布尔型,设置为true以随机化幻灯片
play:0,//数字,自动播放幻灯片,正数将设置为true,并且是以毫秒为单位的幻灯片动画之间的时间
暂停:0,//数字,单击next / prev时暂停幻灯片播放或分页。一个正数将被设置为true并且是以毫秒为单位的暂停时间
hoverPause:false,//布尔值,设置为true并且悬停在幻灯片上将会暂停它
autoHeight:false,//布尔值,Set设为自动调整高度
autoHeightSpeed:350,//数字,以毫秒为单位设置自动高度动画时间
bigTarget:false,//布尔值,设置为true,整个幻灯片将链接到下一张幻灯片单击
animationStart:function(){},//在动画开始时调用的函数
animationComplete:function(){},//动画完成时调用的函数
slidesLoaded:function (){} //当幻灯片完全加载时调用函数
};

//在加载时随机化幻灯片顺序
$ .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){
$ $ $ = $ children.eq(k);
var $ clone = $ child.clone(true);
$ clone.show()。appendTo($ this); $ b $如果(回调!==未定义){
回调($ child,$ clone);
}
$ child.remove();
});
}
}));
};
})(jQuery);


解决方案

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

没有任何原因是因为他从不公开你试图调用的方法(有些甚至不存在)。 Calling slides without the play option will prevent autoplaying, but it will also initialize slidejs (wrapping the children of the container). Calling it again later will re-initialize it thus resulting it the double wrapping you mentioned.



In version 2, he added an API that would work for you:

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

Aside from that, you clearInterval code could also be written as:

$(’.slides’).each(function() { clearInterval($(this).data(\"interval\")); }); 


I'm using slidesjs to create 5 different slideshows/galleries on a single-page site. They all have the class '.slides' and have their own ID.

I do not want any of the slideshows to play until a play function is called. I've been able to successfully prevent each slideshow from playing onload using the following:

    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'));
}

(Using class '.slides' does not stop the slideshows, hence using IDs.) However, I'm now unable to play any of the slideshows. I've tried the following:

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);
}

Your suggestions would be gratefully received as I've been working on this for days now(!). I appreciate I may not be preventing the slideshows from playing in the most elegant way. The full slides.jquery.js is here:

    /*
* 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);

解决方案

I'd suggest using (or taking a look at) Slidejs 2 https://github.com/nathansearles/Slides.

Reason none of of what you're trying is working is because he never exposes those methods you're trying to call (some don't even exist). Calling slides without the play option will prevent autoplaying, but it will also initialize slidejs (wrapping the children of the container). Calling it again later will re-initialize it thus resulting it the double wrapping you mentioned.

In version 2, he added an API that would work for you:

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

Aside from that, you clearInterval code could also be written as:

$('.slides').each(function() { clearInterval($(this).data("interval")); });

这篇关于如何停止和玩jQuery脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆