在foreach循环后初始化插件
Initializing a plugin AFTER a foreach loop
所以我试图实现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属性设置之前附加,这里不这样做,但在这种情况下,它似乎对我来说不是问题。
相关文章:
- 对插件初始化后动态加载的元素进行样式设置
- 通过删除其相关的 DOM 存在来重新初始化 jQuery 插件
- 在尝试SE OAuth初始化时,Firefox插件中出现channelUrl错误
- jQuery插件-初始化后更新设置
- 初始化插件使用 .each 和仅 selector.initplugin 有什么区别
- 余烬组件,如何等待随机jQuery插件初始化
- ReactJS - 在 react 类中初始化 jquery 插件的标准方法是什么
- jQuery scrollbar 插件 (mCustomScrollbar) 不会在 AJAX 回调时重新初始化
- 在 AJAX 页面更新后重新初始化 jQuery 插件
- 是否可以在 ajax 调用后重新初始化 jQuery 的所有插件
- 动态$scope DOM 元素尚未准备好进行插件初始化
- 为什么插件没有动态初始化
- ng 重复后初始化 AngularJS 插件
- 将插件初始化和函数分组到单个脚本中
- 如何为Firefox插件初始化SQLite文件
- 从数据属性初始化JQuery插件
- 使用Angular指令初始化多个jQuery插件
- 第一个jQuery插件 - 如何处理重新初始化时的事件
- 初始化插件后执行jQuery代码
- 在foreach循环后初始化插件