您的位置:首页 > Web前端 > JavaScript

JS_常用代码片段

2009-12-11 10:14 459 查看
1。查找元素位置

var getPagePos = function( el ){
var top = 0, left = 0, D = document;
if( el.getBoundingClientRect ){
top =  el.getBoundingClientRect().top + Math.max(D.documentElement.scrollTop, D.body.scrollTop);
left =  el.getBoundingClientRect().left + Math.max(D.documentElement.scrollLeft, D.body.scrollLeft);
}
else {
top = el.offsetTop, left = el.offsetLeft;
parentNode = el.offsetParent;
if( parentNode != el ){
while ( parentNode ) {
top += parentNode.offsetTop;
left += parentNode.offsetLeft;
parentNode = parentNode.offsetParent;
}
}

}
return { x: left , y: top };
}


2。得到字节长度

// 得到字节长度
String.prototype.bytes = function()
{
return this.replace(/[^/x00-/xff]/g,"--").length;
}


3。延迟调用

Function.prototype.defer = function(delay, args){
var $pointer = this;
if(!(args instanceof Array))
args = [args];
window.setTimeout(function(){
return $pointer.apply(this, args);
}, delay);
}


4。获得浏览器屏幕窗口的大小

//获得浏览器屏幕窗口的大小
window.clientRect = function()
{
var w = (window.innerWidth) ? window.innerWidth :
(document.documentElement && document.documentElement.clientWidth)
? document.documentElement.clientWidth : document.body.offsetWidth;
var h = (window.innerHeight) ? window.innerHeight :
(document.documentElement && document.documentElement.clientHeight)
? document.documentElement.clientHeight : document.body.offsetHeight;
return {width:w,height:h};
}


5。返回参数及参数表

//$pack函数当参数个数为1的时侯返回该参数,否则返回一个参数表
var $pack = function(){
if(arguments.length == 1)
return arguments[0];
else
return Array.apply(null, arguments);
}


6。简单浏览器判断

//判断是否是IE浏览器
function $isIE()
{
return /msie/i.test(navigator.userAgent);
}
//判断是否是Firefox浏览器
function $isFF()
{
return /firefox/i.test(navigator.userAgent);
}
//判断是否是IE7.0浏览器
function $isIE7()
{
return /msie 7/i.test(navigator.userAgent);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: