jQuery-CSS類屬性操作
阿新 • • 發佈:2018-12-21
jQuery 操作 CSS
jQuery 擁有若干進行 CSS 操作的方法。我們將學習下面這些:
- addClass() - 向被選元素新增一個或多個類
- removeClass() - 從被選元素刪除一個或多個類
- toggleClass() - 對被選元素進行新增/刪除類的切換操作
jQuery addClass() 方法
下面的例子展示如何向不同的元素新增 class 屬性。當然,在新增類時,您也可以選取多個元素:
<script> $(document).ready(function(){ $("button").click(function(){ $("h1,h2,p").addClass("blue"); $("div").addClass("important"); }); }); </script> <style type="text/css"> .important { font-weight:bold; font-size:xx-large; } .blue { color:blue; } </style> </head> <body> <h1>標題 1</h1> <h2>標題 2</h2> <p>這是一個段落。</p> <p>這是另外一個段落。</p> <div>這是一些重要的文字!</div> <br> <button>為元素新增 class</button> </body>
您也可以在 addClass() 方法中規定多個類:
<script> $(document).ready(function(){ $("button").click(function(){ $("body div:first").addClass("important blue"); }); }); </script> <style type="text/css"> .important { font-weight:bold; font-size:xx-large; } .blue { color:blue; } </style> </head> <body> <div id="div1">這是一些文字。</div> <div id="div2">這是一些文字。</div> <br> <button>為第一個 div 元素新增類</button> </body>
jQuery removeClass() 方法
下面的例子演示如何在不同的元素中刪除指定的 class 屬性:
<script> $(document).ready(function(){ $("button").click(function(){ $("h1,h2,p").removeClass("blue"); }); }); </script> <style type="text/css"> .important { font-weight:bold; font-size:xx-large; } .blue { color:blue; } </style> </head> <body> <h1 class="blue">標題 1</h1> <h2 class="blue">標題 2</h2> <p class="blue">這是一個段落。</p> <p>這是另外一個段落。</p> <br> <button>從元素中移除 class</button> </body>
jQuery toggleClass() 方法
下面的例子將展示如何使用 jQuery toggleClass() 方法。該方法對被選元素進行新增/刪除類的切換操作:
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").toggleClass("main");
});
});
</script>
<style type="text/css">
.main
{
font-size:120%;
color:red;
}
</style>
</head>
<body>
<h1 id="h1">This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button class="btn1">切換段落的 "main" 類</button>
</body>