$(function() { setImgHeight(); $(window).bind('resize', function() { setImgHeight(); }); $('#list-swap').click(function() { var currType = $(this).html().indexOf('文字') != -1 ? "img" : "text"; if (currType == 'img') { $(this).html("图片列表"); $('#main').removeClass('img-list'); $('#main').addClass('text-list'); } else { $(this).html("文字列表"); $('#main').removeClass('text-list'); $('#main').addClass('img-list'); } }); Limg(); }); window.onscroll = function() { Limg(); }; function Limg() { var viewHeight = document.documentElement.clientHeight; var divs = document.querySelectorAll("div[bgimg]") Array.prototype.forEach.call(divs, function(item, index) { if (item.getAttribute("bgimg") === "") return; var rect = item.getBoundingClientRect(); if (rect.bottom >= 0 && rect.top < viewHeight + 200) { (function() { var img = new Image(); img.src = item.getAttribute("bgimg"); img.onload = function() { $(item).css("background-image", "url(" + img.src + ")"); }; item.removeAttribute('bgimg'); })(); } }) } function setImgHeight() { $('.imgwrap').each(function() { $(this).css('height', (parseInt($(this).css('width'))) * 10 / 16); }); }