如何使用jQuery從特定頁面移除全域性CSS檔案?
程式設計師在開發網頁時需要使用CSS來為網頁設定樣式並使其更具吸引力。我們可以透過三種方式將CSS新增到網頁:內聯CSS、內部CSS和外部CSS。要應用外部CSS,我們可以使用<link>標籤在<head>標籤中匯入CSS檔案。外部CSS檔案也可以是全域性CSS檔案。
有時,我們需要從特定網頁中移除全域性CSS檔案。例如,您允許您的Web應用程式使用者在多個主題之間切換,當用戶切換主題時,您需要移除舊的CSS檔案並根據主題新增新的CSS檔案。
在這裡,我們將學習使用JQuery從特定頁面移除全域性CSS檔案的不同方法。
使用JQuery的remove()方法
在第一種方法中,我們使用find()和remove()方法從特定網頁中移除全域性CSS檔案。我們可以使用<link>標籤將全域性CSS檔案新增到網頁並賦予其唯一的ID。
在JQuery中,我們可以使用ID查詢元素並執行remove()方法以從<head>部分移除<link>標籤。
語法
使用者可以按照以下語法使用find()和remove()方法從特定網頁中移除全域性CSS檔案。
$('head').find('link#unique_id').remove();
在上述語法中,“unique_id”等於包含全域性CSS檔案URL的“<link>”標籤的ID。
示例
在這個例子中,我們在test.html檔案中添加了HTML內容。此外,我們將與HTML內容相關的CSS新增到“style1.css”檔案中。
在JQuery中,我們訪問網頁的“head”部分,並嘗試查詢包含“global”ID的“link”標籤。之後,我們執行remove()方法來移除CSS檔案。
在輸出中,使用者可以單擊按鈕並觀察到網頁中的所有CSS都將消失,因為我們移除了全域性CSS檔案。
檔名 – test.html
<html>
<head>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"> </script>
<link rel = "stylesheet" href = "C:\Data E\style1.css" id = "global">
</head>
<body>
<h2> Removing the <i> Global CSS files </i> using the jQuery </h2>
<p> This is the paragraph. </p>
<div class = "first">
This is a text inside the div element.
</div>
<br>
<button id = "btn"> Remove the Global CSS files </button>
<script>
$(document).ready(function () {
$("#btn").click(function () {
$('head').find('link#global').remove();
});
});
</script>
</html>
檔名 – style1.css
.first {
background-color: red;
font-size: 20px;
font-weight: bold;
width: 200px;
height: 200px;
}
p {
color: blue;
font-size: 20px;
}
使用attr()方法新增“disabled”屬性到連結
從特定網頁移除全域性CSS檔案的另一種方法是使用attr()方法。attr()方法允許我們為HTML元素設定任何屬性。我們可以將“disabled”屬性設定為包含全域性CSS檔案的“<link>”標籤。
語法
使用者可以按照以下語法將“disabled”屬性新增到link標籤,以從特定網頁移除全域性CSS檔案。
$('link[href*="filename"]').attr("disabled", "true");
在上述語法中,“filename”應替換為實際的檔名,以選擇包含全域性CSS檔名的“link”標籤。
示例
在下面的示例中,我們將HTML內容新增到網頁,並將CSS新增到外部CSS檔案。在JQuery中,我們在按鈕上添加了“click”事件。因此,每當使用者單擊按鈕時,他們將訪問包含“style1.css”字串的<link>標籤,並向其新增“disabled”屬性。
使用者可以單擊輸出中的按鈕,並觀察到CSS將被移除,因為全域性CSS檔案被移除了。
檔名 – test.html
<html>
<head>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"> </script>
<link rel = "stylesheet" href = "C:\Data E\style1.css" id = "global">
</head>
<body>
<h2> Removing the <i> Global CSS files </i> using the JQuery's attr() method and disabled attribute of HTML.
</h2>
<p> Click on the button to remove the Global CSS files. </p>
<br>
<button id = "btn"> Remove the Global CSS files </button>
<script>
$(document).ready(function () {
$("#btn").click(function () {
$('link[href*="style1.css"]').attr("disabled", "true");
});
});
</script>
</html>
檔名 – style1.css
p {
color: green;
font-size: 1.3rem;
font-weight: bold;
border: 3px solid green;
}
使用者學習了使用兩種不同的方法從特定網頁移除全域性CSS檔案。在第一種方法中,我們使用remove()方法移除link標籤;在第二種方法中,我們使用attr()方法向link標籤新增“disabled”屬性。
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP