Javascript 獲得元素位置&&獲得元素樣式值-網上找的,方便以後查閱

// 獲得元素樣式
function attrStyle(elem,attr){
    if("undefined" != typeof elem && "undefined" != typeof elem.style){
        //若樣式存在於html中,優先獲取
        return elem.style[attr];
    }else if(elem.currentStyle){
        //IE下獲取CSS屬性最終樣式(同於CSS優先級)
        return elem.currentStyle[attr];
    }else if(document.defaultView && document.defaultView.getComputedStyle){
        //W3C標準方法獲取CSS屬性最終樣式(同於CSS優先級)
        //注意,此法屬性原格式(text-align)獲取的,故要轉換一下
        attr=attr.replace(/([A-Z])/g,'-$1').toLowerCase();
        //獲取樣式對象並獲取屬性值
        return document.defaultView.getComputedStyle(elem,null).getPropertyValue(attr);
    }else{
        return null;
    }
}
attrStyle(document.getElementById("coorDiv"), "margin-left");


// 獲得元素位置

function elementLeft(e){
	var offset = e.offsetLeft;
	if(e.offsetParent != null) offset += elementLeft(e.offsetParent);
	return offset;
}

function elementTop(e){
	var offset=e.offsetTop;
	if(e.offsetParent != null) offset += elementTop(e.offsetParent);
	return offset;
}

function elementPos(e){
	return {left:elementLeft(e), top:elementTop(e)};
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章