有時候我們需要讓用戶自己決定要改哪個屬性、改成什麼值——比如一個調色或調距的調試面板。這類功能的關鍵是把「屬性名」和「屬性值」都當作參數傳進函數,而不是寫死。
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"); // 重置:直接移除整個 style 屬性
};
};
這裡用 elem.style[name] = value 而不是 setAttribute('style', ...),是因為前者只改一條聲明,不會把其他已有樣式一起沖掉。
$(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");
});
});
<!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">
$(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>
backgroundColor 而不是 background-color;jQuery 的 css() 兩種寫法都接受。opacity 時,jQuery 會自動補上 filter: alpha(opacity=x) 以兼容舊 IE,原生寫法則需要自己處理。px,否則會被忽略。removeAttr("style"):如果元素有其他內聯樣式需要保留,改成 removeProperty('background') 或 $("#div1").css(name, "") 更精準。