gpt4 book ai didi

javascript - 使用 knockoutjs 延迟加载图像

转载 作者:行者123 更新时间:2023-11-30 05:35:01 25 4
gpt4 key购买 nike

我正在尝试使用 knockoutjs 绑定(bind)延迟加载图像。我能够在没有 knockoutjs 框架的情况下延迟加载图像,但我不确定如何使用 knockoutjs 绑定(bind)来做到这一点。这是我的 HTML

     <div class='liveExample'> 
<div class="row">
<div data-bind="foreach: items">
<div class="col-lg-4 col-md-4 col-sm-4 " style="padding: 0px">
<img data-bind=" attr: { src: $data }" class="lazy" />
</div>
</div>
</div>
</div>

Javascript:

var SimpleListModel = function(items) {
this.items = ko.observableArray(items);
bind(this); // Ensure that "this" is always this view model
};

var pictures = []; //Initialise an empty array

for (var i = 0; i = 10 ; i++) {
var image; //This is a placeholder
image = 'http://dummyimage.com/300x200/000/fff&text=' + i; //Set the src attribute (imageFiles[i] is the current filename in the loop)
pictures.push(image); //Append the new image into the pictures array
}

ko.applyBindings(new SimpleListModel(pictures));

这是 jsfiddle

最佳答案

我通过在 foreach 绑定(bind)之前添加额外的 div 标签并将 afterrender 事件分配给父 div 使其工作

   <div class="row">
<div data-bind='template: {afterRender: myPostProcessingLogic }'>
<div data-bind="foreach: {data: items} ">
<div class="col-lg-4 col-md-4 col-sm-4 " style="padding: 0px">
<img data-bind=" attr: { 'data-original': $data }" class="lazy" style="min-width:100px; min-height:50px;" />
</div>
</div>
</div>

</div>

Javascript

var SimpleListModel = function(items) {
this.items = ko.observableArray(items);
this.myPostProcessingLogic = function(elements) {
$("img.lazy").lazyload({
effect: "fadeIn",
effectspeed: 2000
});
}
};

var pictures = []; //Initialise an empty array
for (var i = 1; i < 100 ; i++) {
var imageUrl = 'http://dummyimage.com/300x200/000/fff&text=' + i; //Set the image url
pictures.push(imageUrl); //Append the new image into the pictures array
}
ko.applyBindings(new SimpleListModel(pictures));

这是 jsfiddle

关于javascript - 使用 knockoutjs 延迟加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24414616/

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