DOMReady函数,只要DOM结构加载完成即可,不必等待所有资源加载完成,节约时间,"DOMContentLoaded"在H5中被标准化
var DOMReady=function(f,a,d){ d = d || document; a = a || "addEventListener"; d[a]?d[a](‘DOMContentLoaded‘,f,false):window.attachEvent(‘onload‘,f); } DOMReady(function(){ alert("The DOM is Ready"); })
检查元素是否在视窗(分完全在视窗内,部分在视窗内以及完全不在视窗内)
function isInViewPort(ele){ var rect=ele.getBoundingClientRect(); alert(rect.top+","+rect.right+","+rect.bottom+","+rect.left); var newRect=getRect(ele); alert(newRect.top+","+newRect.right+","+newRect.bottom+","+newRect.left); return rect.top < (window.innerHeight || document.documentElement.clientHeight) && rect.right < (window.innerWidth || document.documentElement.clientWidth) && rect.bottom < (window.innerHeight || document.documentElement.clientHeight) && rect.left < (window.innerWidth || document.documentElement.clientWidth); }
IE7及以下浏览器的坐标从(2,2)开始计算,需要提供兼容方案
function getRect(ele){ var rect=ele.getBoundingClientRect(); var top=document.documentElement.clientTop; //IE=2 非IE=0 var left=document.documentElement.clientLeft; //IE=2 非IE=0 return{ top:rect.top-top, bottom:rect.bottom-top, left:rect.left-left, right:rect.right-left } }
原文:http://www.cnblogs.com/diantao/p/4937411.html