在foreach循环后初始化插件

Initializing a plugin AFTER a foreach loop

本文关键字:初始化 插件 循环 foreach      更新时间:2023-09-26

所以我试图实现stellar.js,但它必须在每个循环完成后初始化。循环必须将data属性添加到将要由插件产生视差的图像中。

图片在一个列表中:

<ul>
    <li class="item">
        <div class="item-image" data-stellar-background-ratio="0.7" data-image="http://picjumbo.picjumbocom.netdna-cdn.com/wp-content/uploads/IMG_7706-1300x866.jpg"></div>
    </li>
    ...
</ul>

我必须添加data- star -vertical-offset属性,这将使图像偏移一半的高度,因此它可以垂直居中。

JS:

/* Inserting the background image */
$('.item-image').each(function () {
var $this = $(this);
$this.css('background-image', 'url(' + $this.data('image') + ')');
})
 /* Creating loop that will run as many times as items are in there */
var items = $('.item-image').length;
var currentItem = 0;
$('.item-image').each(function () {
var $this = $(this);
/* Taking the origin height, halving it and putting it as offset so the image can be vertically aligned */
var img = new Image();
img.src = $(this).data('image');
img.onload = function () {
    var H2 = this.height;
    $this.attr('data-stellar-vertical-offset', -(H2 / 2));
}
currentItem++;
/* Initializing the plugin after every item is looped */
if (currentItem >= items) {
        $.stellar();
}
})

然而,当插件初始化时,它不使用data属性。如果像这样输入超时:

 if (currentItem >= items) {
    setTimeout(function () {
        $.stellar();
    }, 10)
}

. .它可以工作,但在我看来,它是一个丑陋的黑客。有没有更好的方法来做到这一点?

jsfiddle : http://jsfiddle.net/9f2tc/1/

我相信您想要的是在下载完所有图像后初始化恒星。最简单的方法是每次在onload处理程序中检查一次:

img.onload = function () {
    var H2 = this.height;
    $this.attr('data-stellar-vertical-offset', -(H2 / 2))
    if (++currentItem === items) {
        $.stellar();   
    }
}

jsfiddle: http://jsfiddle.net/X6e9n/2/

然而,在某些情况下onload事件不触发图像是有问题的。列出的问题不仅适用于jQuery的.load(),还适用于load事件本身。请参阅Javascript回调,了解何时加载图像以获得解决方案。第一个答案指出,处理程序应该在src属性设置之前附加,这里不这样做,但在这种情况下,它似乎对我来说不是问题。