DIV CSS 佈局教程網

elementGetStyle(element, style) 取得元素樣式的應用示例
編輯:關於JavaScript     

下面的函式用來取得 DOM 元素 Style 陣列中指定的樣式值,並能相容不同瀏覽器的取值方式。

取得元素樣式

function elementGetStyle(element, style) {
var value = null;
if (element.style) {
value = element.style[style];
}
if (!value) {
if (document.defaultView && document.defaultView.getComputedStyle) {
var css = document.defaultView.getComputedStyle(element, null);
value = css ? css.getPropertyValue(style) : null;
} else if (element.currentStyle) {
value = element.currentStyle[style];
}
}
return value == 'auto' ? null : value;
}

它先嘗試讀取行內樣式,接著對標準瀏覽器使用 getComputedStyle,對舊版 IE 則退回 currentStyle,最後把 auto 統一轉為 null。

高亮選定元素

下一個函式會把選定的 DOM 元素以指定顏色(預設黃色)高亮約 0.2 秒後還原:

function UiWebhighlight(element,color) {
if (!element) {return}
var highLightColor = "yellow";
if (color) {highLightColor = color}
if (element.originalColor == undefined) { // avoid picking up highlight
element.originalColor = elementGetStyle(element, "background-color");
}
elementSetStyle(element, {"backgroundColor" : highLightColor});
window.setTimeout(function () {
try {
//如果元素已經是孤兒節點,可能頁面已經消失,就忽略
if (!element.parentNode) {
return;
}
elementSetStyle(element, { "backgroundColor": element.originalColor });
} catch (e) { } // 取消高亮風險較低,可靜默處理
}, 200);
}

使用時,它會先記住元素原本的背景色,套用高亮色,再透過 setTimeout 在 200 毫秒後還原,適合用來在頁面上標示當前操作的目標元素。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved