DIV CSS 佈局教程網

原生 JS 與 jQuery:動態修改 div 樣式屬性與還原
編輯:關於JavaScript     

下面用幾個簡單的例子,示範如何用原生 JavaScript 與 jQuery 動態改變一個 div 的樣式屬性,以及如何一鍵還原(重置)這些樣式。

<!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 changeSytle = 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 (){
changeSytle (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>

程式解析

這個範例提供了一個「屬性名 + 屬性值」的輸入介面。使用者填入想要的樣式名稱(例如 background)與值(例如 blue),按下「確定」後就會套用到目標 div 上。

原生 JS 版本的核心是一個自訂的 changeSytle 函式,透過 elem.style[name] = value 動態賦值;重置則用 oDiv.removeAttribute("style") 一次清掉所有行內樣式。

jQuery 版本更為簡潔:$("#div1").css(styleName, styleVal) 一行就能設定樣式,而 $("#div1").removeAttr("style") 則負責還原。兩種寫法效果一致,可依專案是否已引入 jQuery 來選擇。

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