`
阅读更多

使用javascript如何获取页面滚动条呢?

(1)获取页面滚动条

// Cross browser gets the position of scroll
com.whuang.hsj.getScroll=function(){
    return {
        top:document.documentElement.scrollTop || document.body.scrollTop,
        left:document.documentElement.scrollLeft || document.body.scrollLeft,
        height:document.documentElement.scrollHeight ||document.body.scrollHeight
    }
}

 

(2)获取iframe滚动条

/***
* get iframe window'scroll
*/
com.whuang.hsj.getIframeScroll=function(iframeObj){
	var document22=iframeObj.contentWindow.document;
    return {
        top:document22.documentElement.scrollTop || document22.body.scrollTop,
        left:document22.documentElement.scrollLeft || document22.body.scrollLeft,
        height:document22.documentElement.scrollHeight || document22.body.scrollHeight,
        width:document22.documentElement.scrollWidth || document22.body.scrollWidth
    }
}

 

(3)获取div滚动条

/***
 * Get scroll of div
 * @param divObj
 * @returns {{scrollHeight: (*|number), scrollWidth: (*|number)}}
 */
com.whuang.hsj.getDivScroll=function(divObj){
    if(typeof divObj == 'string'){
        divObj=com.whuang.hsj.$$id(divObj);
    }
    return {
        scrollHeight:divObj.scrollHeight,
        scrollWidth:divObj.scrollWidth
    }
}

 

(4)获取div的位置

/***
 * Get the Coordinate/Location of div
 * @param divObj
 * @returns {{width: number, height: number, left: *, top: Window}}
 */
com.whuang.hsj.divCoordinate=function(divObj){
    if(typeof divObj == 'string'){
        divObj=com.whuang.hsj.$$id('divObj');
    }
    return {'width':divObj.offsetWidth,'height':divObj.offsetHeight,
        'x':divObj.offsetLeft,'y':divObj.offsetTop,
        'scrollLeft':com.whuang.hsj.getScroll().left,'scrollTop':com.whuang.hsj.getScroll().top};
}

 

参考:利用函数的惰性载入提高javascript代码性能

http://blogread.cn/it/article/7304?f=hot1

 -------------- 2016年3月7日更新 --------------

跨浏览器设置滚动条的竖直位置

com.whuang.hsj.setTopScroll=function(top){
	if(document.documentElement.scrollTop){
		document.documentElement.scrollTop=top;
	}else if(document.body.scrollTop){
		document.body.scrollTop=top;
	}
};

 

跨浏览器设置滚动条的水平位置

com.whuang.hsj.setLeftScroll=function(left){
	if(document.documentElement.scrollLeft){
		document.documentElement.scrollLeft=left;
	}else if(document.body.scrollLeft){
		document.body.scrollLeft=left;
	}
};

 

 

  • js.zip (16.1 KB)
  • 下载次数: 4
0
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics