有時候我們希望讓使用者自己決定要改哪個樣式屬性、改成什麼值,例如一個簡單的調色或調字級的小工具。做法是把「屬性名」與「屬性值」當參數傳進函式,再動態套用到元素上,並附一個重置按鈕。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>函數傳參,改變 Div 任意屬性的值</title>
<style type="text/css">
body,p{margin:0;padding:0;}
body{color:#333;font:12px/1.5 Tahoma;padding-top:10px;}
#outer{width:300px;margin:0 auto;}
p{margin-bottom:10px;}
button{margin-right:5px;}
label{width:5em;display:inline-block;text-align:right;}
input{padding:3px;font-family:inherit;border:1px solid #ccc;}
#div1{color:#fff;width:180px;height:180px;background:#000;margin:0 auto;padding:10px;}
</style>
<script type="text/javascript" src="js/jquery-1.4.2.min.js"</script>
<script type="text/javascript">
// 原生 JS 版本
var changeStyle = function (elem, name, value) {
elem.style[name] = value;
};
window.onload = function () {
var oDiv = document.getElementById("div1");
var oBtn = document.getElementsByTagName("button");
var oInput = document.getElementsByTagName("input");
oBtn[0].onclick = function () {
changeStyle(oDiv, oInput[0].value, oInput[1].value);
};
oBtn[1].onclick = function () {
oDiv.removeAttribute("style"); // 重置:移掉所有行內樣式
};
};
// jQuery 版本
$(function(){
$("button:first").click(function(){
var styleName = $("#outer").find("input:first").val();
var styleVal = $("#outer").find("input:last").val();
$("#div1").css(styleName, styleVal);
});
$("button:last").click(function(){
$("#div1").removeAttr("style");
});
});
</script>
</head>
<body>
<div id="outer">
<p><label>屬性名:</label><input type="text" value="background" name="styleName" /></p>
<p><label>屬性值:</label><input type="text" value="blue" name="val" /></p>
<p><label></label><button>確定</button><button>重置</button></p>
</div>
<div id="div1">在上方輸入框輸入「屬性名」及「屬性值」,點擊確定按鈕查看效果。</div>
</body>
</html>
兩種寫法的核心一致:把使用者輸入的字串直接當成 style 的鍵。原生版用 elem.style[name] = value,jQuery 版用 $el.css(name, value)。
第一,原生 JS 中 style 的屬性名必須用駝峰式(backgroundColor),CSS 裡的 background-color 直接塞進去是無效的;jQuery 的 .css() 則兩種都吃,它會幫你轉換。
第二,數值型屬性若要帶單位,記得一起輸入(如 20px)。jQuery 對部分屬性會自動補 px,原生 JS 不會。
第三,這個範例刻意允許任意屬性名輸入,若放到真實產品上,使用者輸入不存在的屬性會靜默失敗,輸入 cssText 這類特殊鍵甚至有覆蓋整份行內樣式的風險。比較穩妥的做法是提供下拉選單限定可改的屬性,並用白名單驗證。
另外,範例中同時引入 jQuery 與原生版本,實際專案只擇一即可;重置用 removeAttribute("style") 會連帶清掉原本寫在標籤上的行內樣式,若只想還原到「初始狀態」,應該先把初始樣式存起來再逐項覆寫回去。