網頁載入圖片完成後...
這個功能需求是為了相簿使用了瀑布流計算圖片高度,因為等寬不等高所以必須等圖片實際載入完成才知道確切高度。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" href="/Component_Front/bootstrap/css/bootstrap.min.css"/> <script src="/Component_Front/jquery-1.11.3.min.js"></script> <script src="/Component_Front/jquery-tmpl-master/jquery.tmpl.min.js"></script> <script src="/Component_Front/imagesloaded.pkgd.min.js"></script> <style> .box{ padding: 15px 0 0 15px; float:left; } .pic{ padding: 10px; border:1px solid #ccc; box-shadow: 0 0 6px #ccc; border-radius: 5px; } .pic img{ width: 180px; height:auto; } </style> </head> <body> <div> <p>Container height: <span id="containerHeight"></span></p> <div id="Main"></div> <script id="Template" type="text/template"> <div class="box"> <div class="pic"><img src="${src}" alt=""/></div> <div class="text"></div> </div> </script> </div> <script> $.post('Json.php', {}, function(Json){ $('#Template').tmpl(Json).appendTo('#Main'); }, 'json').done(function(){ // 圖片載入完成後 取得最後真正高度 $('.box').imagesLoaded( function() { $('#containerHeight').html($(document).height()); }); }); </script> </body> </html> |
--
AngularJS
$timeout 的延遲時間必須足夠讓圖片載入完成,得到的高度才會是正確的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
<!DOCTYPE html> <html ng-app="myApp"> <head lang="en"> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" href="/Component_Front/bootstrap/css/bootstrap.min.css"/> <script src="/Component_Front/jquery-1.11.3.min.js"></script> <script src="/Component_Front/angular-1.5.5/angular.min.js"></script> <style> .box{ padding: 15px 0 0 15px; float:left; } .pic{ padding: 10px; border:1px solid #ccc; box-shadow: 0 0 6px #ccc; border-radius: 5px; } .pic img{ width: 180px; height:auto; } </style> </head> <body> <div ng-controller="myCtrl"> <p>Container height: {{containerHeight}}</p> <div class="box" ng-repeat="post in posts"> <div class="pic"><img ng-src="{{post.src}}" alt=""/></div> <div class="text"></div> </div> </div> <script> var app = angular.module('myApp', []); app.controller("myCtrl", ['$scope', '$http', '$timeout', function($scope, $http, $timeout) { $http.get('Json.php'). success(function(data, status, headers, config) { $scope.posts = data; }). error(function(data, status, headers, config) { // log error }); $timeout(function () { $scope.containerHeight = $(document).height(); }, 1000); }]); </script> </body> </html> |
--
677 total views, 1 views today