lazyLoad

本文介绍了一个使用Angular实现的图片懒加载示例。通过Angular的服务和控制器来控制页面上多个图片的懒加载效果,当图片进入可视区域时,它们会从占位符图像平滑过渡到实际图像。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="angular.min.js"></script>
<script src="jquery.min.js"></script>
</head>
<body ng-app="myApp">

<div ng-controller="myController">
<div style="height: 500px" ng-repeat="x in menuListData" class="menuDiv">
<img style="height: 100%" class="menuImg" src="fill.jpg" dataSrc="{{x}}">
</div>
</div>

</body>

<script>
var app = angular.module('myApp', []);
//定义服务
app.service('commonFun', function ($http) {
this.elementLazyload = function (positionSelector, targetSelector,targetAttributeName, srcAttributeName,srcUrl) {
var elements = $(positionSelector);
var targetElements = $(targetSelector);
console.info("targetElements.length == " + targetElements.length);

var num = elements.length;
console.info("num == " + num);
var n = 0; //存储图片加载到的位置,避免每次都从第一张图片开始遍历

function lazyloadDeal() {
var windowHeigh = $(window).height();
var scrollTopHeigh = $(document).scrollTop();
console.info("windowHeigh == " + windowHeigh);
console.info("scrollTopHeigh == " + scrollTopHeigh);

for (var i = n; i < num; i++) {
//console.info("elementsoffsetTop == " + elements[i].offsetTop + " i== " + i);
//console.info("windowHeigh + scrollTopHeigh == " + (windowHeigh + scrollTopHeigh));
//if (elements[i].offsetTop < windowHeigh + scrollTopHeigh) {
if (elements[i].offsetTop < windowHeigh + scrollTopHeigh) {
if (targetElements[i].getAttribute(targetAttributeName) == srcUrl) {
//console.info("windowHeigh ============================================== i == " + i);
targetElements[i].setAttribute(targetAttributeName, targetElements[i].getAttribute(srcAttributeName))
}
n = i + 1;
}
}
if (n == num) {
console.info("n == num");
$(window).unbind("scroll",lazyloadDeal);
}
}

$(window).scroll(lazyloadDeal);
lazyloadDeal();
};
});

app.controller('myController', function ($scope, commonFun, $timeout) {
$scope.menuListData = ["ajax1.jpg","ajax2.jpg","ajax3.jpg","ajax4.jpg","ajax5.jpg","ajax6.jpg","ajax7.jpg"];

var timer = $timeout(function () {
commonFun.elementLazyload(".menuDiv",".menuDiv img","src","dataSrc","fill.jpg");
}, 2000); //该函数延迟2秒执行


});
</script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jie310600

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值