<!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>
lazyLoad
猜你喜欢
转载自huangyongxing310.iteye.com/blog/2373515
今日推荐
周排行