在foreach循环之后初始化插件

时间:2014-06-14 16:39:48

标签: javascript jquery each stellar.js

所以我正在尝试实现stellar.js但必须在每个循环完成后初始化它。循环必须将数据属性添加到将由插件进行视差的图像。

图像在列表中:

<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-stellar-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/

1 个答案:

答案 0 :(得分: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页面上的警告部分:http://api.jquery.com/load-event/列出的问题适用于load事件本身,而不仅仅是jQuery的 .load()请参阅Javascript callback for knowing when an image is loaded了解解决方案。第一个答案注意到在设置src属性之前应该附加处理程序,这在这里你没有做,但在这种情况下对我来说似乎不是问题。