學習用 JavaScript 控制 CSS 的 float 屬性時,會遇到一個有趣的相容問題:在 Aptana 沒有程式碼提示,換到 Visual Studio 2008 也一樣沒有。不知道是因為這個屬性在各瀏覽器間不相容,還是編輯器本身有 bug。先看實際的範例。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>測試 float 控制</title>
<script type="text/javascript">
function divFloatRight(e) {
e.style.backgroundColor = "#ff0000";
e.style.styleFloat = "right"; // IE
e.style.cssFloat = "right"; // Firefox 與其他瀏覽器
}
function divFloatLeft(e) {
e.style.backgroundColor = "transparent";
e.style.styleFloat = "left";
e.style.cssFloat = "left";
}
</script>
</head>
<body>
<div>
<div id="demo" style="border:dashed 1px #000000;"
onmousemove="divFloatRight(this);"
onclick="divFloatLeft(this);">
// 用 JavaScript 控制 div 的 float 屬性,
// onmousemove 時 float:right,onclick 時 float:left。
</div>
</div>
</body>
</html>
在這裡,IE 只支援 obj.style.styleFloat,而 Firefox 與其他瀏覽器只支援 obj.style.cssFloat。
為了解決這個相容問題,一開始我還打算正經八百地寫一個瀏覽器判斷的函式,後來反過來一想:只要把這兩個屬性的設定語句寫在一起,就能同時相容各個瀏覽器了。不支援的那一個屬性,瀏覽器只會當它是無效的物件屬性而跳過,不會報錯。
這個思路值得記住:在 JavaScript 裡處理跨瀏覽器差異時,先做「連續賦值」的嘗試,往往比做能力偵測來得簡潔。判斷式越少的程式碼,出錯的面也越小。