如何使用 jQuery 應用 CSS 樣式?


我們可以使用 jQuery 的 .css() 方法在給定的網頁上應用 CSS 樣式。jQuery 是一個 JavaScript 庫,它可以幫助我們使用其各種輔助方法和屬性輕鬆高效地操作 DOM。它允許我們為 DOM 新增互動性,以及新增和更改 DOM 元素的 CSS 樣式。

語法

$(selector).css(property, value)

$(selector).css({ property: value, property: value, … })

JQuery css() 方法接受一個物件型別的引數,其中鍵為 CSS 屬性名稱,值為要設定的目標屬性值,或者只是一對用逗號分隔的 CSS 屬性名稱和值。

讓我們透過一些合適的示例瞭解如何使用 jQuery 的 css() 方法為 HTML 元素應用樣式。

示例 1

在本例中,我們將使用 css() jQuery 方法在點選按鈕後更改“p”標籤的文字顏色。

<!DOCTYPE html>
<html lang="en">
<head>
   <script src="https://code.jquery.com/jquery-3.6.3.slim.min.js" crossorigin="anonymous"></script>
   <title>How to apply CSS style using jQuery?</title>
</head>
<body>
   <p class="sample">This is p tag content!</p>
   <button>Click here!</button>  
   <script>
      const button = document.getElementsByTagName('button')[0]
      button.addEventListener('click', function(){
         $('p').css('color', 'red')
      })
   </script>
</body>
</html>

示例 2

在本例中,我們將使用 jQuery 提供的 css() 方法在點選按鈕後更改“p”標籤的字型顏色和背景顏色。

<!DOCTYPE html>
<html lang="en">
<head>
   <script src="https://code.jquery.com/jquery-3.6.3.slim.min.js" crossorigin="anonymous"></script>
   <title>How to apply CSS style using jQuery?</title>
</head>
<body>
   <p class="sample">This is p tag content!</p>
   <button>Click here!</button>  
   <script>
      const button = document.getElementsByTagName('button')[0]
      button.addEventListener('click', function() {
         $('p').css({ 'color': 'white', 'background-color': 'black' })
      })
   </script>
</body>
</html>

結論

在本文中,我們學習了 jQuery 提供的 css() 方法,並使用它透過 2 個示例為 DOM 元素應用 CSS 樣式屬性。在第一個示例中,我們更改了按鈕點選時內容的“文字顏色”,在第二個示例中,我們更改了按鈕點選時內容的“文字顏色”和“背景顏色”。

更新於: 2023年2月22日

7K+ 瀏覽量

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告