gpt4 book ai didi

javascript - 在 foreach 循环之后初始化插件

转载 作者:行者123 更新时间:2023-12-03 12:25:44 24 4
gpt4 key购买 nike

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

})

但是,当插件初始化时,它不使用数据属性。如果像这样设置超时:

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

关于javascript - 在 foreach 循环之后初始化插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24222051/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com