DIV CSS 佈局教程網

動態修改 div 任意屬性名稱與值的原生 JS 與 jQuery 寫法
編輯:關於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");   // 重置:直接移除整個 style 屬性
    };
};

這裡用 elem.style[name] = value 而不是 setAttribute('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");
    });
});

完整可運行示例

<!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>

幾個實用提醒

  • 用駝峰命名:JS 裡寫 backgroundColor 而不是 background-color;jQuery 的 css() 兩種寫法都接受。
  • 涉及 opacity 時,jQuery 會自動補上 filter: alpha(opacity=x) 以兼容舊 IE,原生寫法則需要自己處理。
  • 數值型屬性(width、top、left 等)在原生寫法中要手動加 px,否則會被忽略。
  • 重置不一定非要 removeAttr("style"):如果元素有其他內聯樣式需要保留,改成 removeProperty('background') 或 $("#div1").css(name, "") 更精準。
  • 如果屬性名在用戶輸入層面完全不可控,注意這只適合內部調試工具;直接將用戶輸入當樣式賦值存在風險,對外場景應改用白名單校驗。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved