首页 > 解决方案 > .destroy (backstretch) 不适用于 ajax 内容

问题描述

我有一个网站,其中有一个滑块的回弹实例(在 div #backstretch 中),从网站本身的一组图像加载。数组如下所示:

<script>
$('#backstretch').backstretch([
[
{ width: 1400, url: "./img/05_1400.jpg" },
{ width: 1000, url: "./img/05_1000.jpg" },
{ width: 780, url: "./img/05_780.jpg" },
{ width: 500, url: "./img/05_500.jpg" }
],
[
{ width: 1400, url: "./img/02_1400.jpg" },
{ width: 1000, url: "./img/02_1000.jpg" },
{ width: 780, url: "./img/02_780.jpg" },
{ width: 500, url: "./img/02_500.jpg" }
]
], {
fade: 2000,
duration: 5000
});
</script>

要在单击时更改此滑块的图像集,我使用 jquery .load() 在我的网站中加载新内容。新内容还有一个包含新图像的数组。要启动加载,滑块下方有一些 .item 类的 div,可单击以开始加载新的图像集。通过单击一个项目,此处的 url 将使用项目索引动态设置。

jQuery(function(){
$(document).on("click", '.item', function(index, element) {
var index = $('.item').index(this);
var singleurl = 'single_' + index + '.html';
var $instance = $('#backstretch').data('backstretch');
$instance.destroy('preserveBackground');
$('#singleview').fadeIn(1500).load(singleurl);    
});

问题是,我第一次更改图像集时效果很好。旧集被破坏,新集正在滑动。但是,如果我单击下一个项目以加载下一个图像,则设置旧图像和第一组图像也会出现在幻灯片中。它们并没有真正被摧毁。我该如何解决?

标签: jqueryjquery-backstretch

解决方案


所以我现在得到了它的工作,在 backstretch 维护者的帮助下。

jQuery(function(e) {
$(document).on("click", '.inneritem', function(index, element) {
var indexe = $('.inneritem').index(this);  // count items
var singleurl = 'single_' + indexe + '.html';  // create url for each item
$('html').animate({scrollTop: '0px'}, 1200).promise().then(function() {     // scroll to top
var $instance = $('#backstretch').data('backstretch');  // get the instance
$instance && $instance.destroy(true);  // destroy it
$('#singleview').fadeIn().load(singleurl);   // load new backstretch slides
});
});
});

目标是将调用和销毁实例放在正确的位置。在我的问题代码中缺少一些代码以使其更简单,但这段代码是主要问题:

$('html, body').animate({scrollTop: '0px'}, 1200, function() {
$('#singleview').fadeIn().load(singleurl);

我想在加载内容之前滚动顶部两次调用 backstretch('html,body')。我以前没看到。.promise().then( 被添加了。现在它就像一个魅力。


推荐阅读