jQuery-CSS類屬性操作

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>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章