我正在使用http://jquery.malsup.com/cycle2/api/,当我检测到移动设备时,我正试图破坏窗口调整大小事件上的cycle2滑块。不幸的是,它返回以下两个错误:
[cycle2] slideshow must be initialized before sending commands; "destroy" ignored
[cycle2] slideshow must be initialized before sending commands; "reinit" ignored
也许有人可以帮忙,我做错了什么?这是代码:
$(function() {
var slider = $('.slider').cycle();
condition = true;
//destroy onload under condition
if(condition){
slider.cycle('destroy');
}
//destroy on resize
$(window).on('resize',function() {
condition = true; //Will be function to recondition let´s say it's true by now
if(condition){
slider.cycle('destroy');
} else {
slider.cycle('reinit');
}
});
});
谢谢。
答案 0 :(得分:2)
看起来你正在破坏这里的滑块:
if(condition){
slider.cycle('destroy');
}
你可以这样做:
$(function() {
var $W = $(window),
slider = $('.slider').cycle();
$W.on('resize',function() {
if ($W.width() < 768) // width of device
slider.cycle('destroy');
});
});
答案 1 :(得分:2)
我知道这是一个老问题,但我也试图解决这个问题,在仔细阅读文档之后,这就是我提出的问题。
所以我使用数据属性在幻灯片上设置我的选项。我非常喜欢这个功能。
为简单起见,这是我打开cycle2 div
<div data-cycle-carousel-visible="3"
data-cycle-carousel-fluid="true"
data-cycle-fx="carousel"
data-cycle-prev="#carousel-prev"
data-cycle-next="#carousel-next"
class="cycle-slideshow cycle-front-page-slideshow"
>
请注意,我确实添加了循环幻灯片类,因此Cycle2自动初始化,然后我还添加了另一类循环前页幻灯片,以防我在我的网站上有其他幻灯片,我可以只针对这一个。< / p>
我的javascript看起来像这样。
function check_window_size( opts ){
// Check if the max-width of window is 899px; window.matchMedia is a native javascript function to check the window size.
var w899 = window.matchMedia( "(max-width: 899px)" );
// if it is max-width of 899px, then set the number of items in the cycle2 carousel slideshow to 2, else show 3
// to see if it matches, you would use the variable and grab the matches array; this will return true or false if window size is max-width 899px
if( w899['matches'] ) {
opts.carouselVisible = 2;
}else{
opts.carouselVisible = 3;
}
}
这是您定位幻灯片的地方(我的使用.cycle-front-page-slideshow类)
// Grab the cycle2 slideshow initialized from the data attributes on the DIV above
$('.cycle-front-page-slideshow').on('cycle-bootstrap', function(e, opts, API) {
// run the check_window_size function to get initial window size, just in case they are max-width 899px already
check_window_size( opts );
// When window is resized, send the options to the check_window_size function so we can manipulate it
window.onresize = function() {
check_window_size( opts );
};
});
另请注意,如果您想使用Carousel功能,则必须从http://jquery.malsup.com/cycle2/download/下载cycle2轮播过渡插件
希望这有助于其他人。