DIV CSS 佈局教程網

原生 JS 與 jQuery 動態修改 div 的 style 屬性與還原
編輯:JQuery特效代碼     

本文分享幾個簡單實例,示範如何用原生 JS 與 jQuery 動態改變 div 的 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>

重點說明

jQuery 版本的核心只有兩行:透過 css(屬性名, 屬性值) 就能動態設定任意樣式,而 removeAttr("style") 則能一次清除所有行內樣式完成重置。相較於原生 JS 需要逐一操作 element.style,jQuery 的寫法明顯更為直覺簡潔,特別適合屬性名稱與值都由使用者輸入的動態場景。

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