【发布时间】: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)
}
.. 它有效,但在我看来,它就像一个丑陋的黑客。有没有更好的方法来做到这一点?
这是一个jsfiddle:http://jsfiddle.net/9f2tc/1/
【问题讨论】:
标签: javascript jquery each stellar.js