【问题标题】:Initializing a plugin AFTER a foreach loop在 foreach 循环之后初始化插件
【发布时间】:2014-06-14 16:39:47
【问题描述】:

所以我正在尝试实现 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-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)
}

.. 它有效,但在我看来,它就像一个丑陋的黑客。有没有更好的方法来做到这一点?

这是一个jsfiddlehttp://jsfiddle.net/9f2tc/1/

【问题讨论】:

    标签: javascript jquery each stellar.js


    【解决方案1】:

    我相信您想要的是在下载完所有图像后初始化一次 Stellar。最简单的方法是在 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/ 列出的问题适用于加载事件本身,而不仅仅是 jQuery 的 .load() 有关解决方案,请参阅 Javascript callback for knowing when an image is loaded。第一个答案指出,应该在设置 src 属性之前附加处理程序,您在这里没有这样做,但在这种情况下,这对我来说似乎不是问题。

    【讨论】:

    • 我必须为每个图像初始化 stellar() 为 $this.stellar(); 还是之后只需要一次?
    • 是的,你是对的。为每个图像初始化 stellar 什么都不做,因为它会相对于未滚动的图像的滚动重新定位图像,因此永远不会重新定位图像。我已经用这个变化更新了小提琴和代码 sn-p。
    • 谢谢,你一直很有用!
    猜你喜欢
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    相关资源
    最近更新 更多