首頁 > web前端 > css教學 > 主體

如何使用 JavaScript 從 Body 將樣式表注入 Head ?

Barbara Streisand
發布: 2024-11-14 19:34:02
原創
567 人瀏覽過

How to Inject a Stylesheet into the Head with JavaScript from the Body?

Injecting Stylesheet into Head with JavaScript in Body

The inability to edit the section of a CMS can pose a challenge when needing to add a CSS stylesheet to a website. This issue can be resolved by utilizing JavaScript to inject the stylesheet directly into the section, even if the script itself is appended to the end of the tag.

To achieve this, a new element is created dynamically using JavaScript. This element is configured with the appropriate attributes:

  • type: "text/css"
  • rel: "stylesheet"
  • href: The URL of the stylesheet to be loaded

Once created, the element is appended to the section using the appendChild() method on the Document.head object.

Example:

function addCss(fileName) {
  const head = document.head;
  const link = document.createElement("link");

  link.type = "text/css";
  link.rel = "stylesheet";
  link.href = fileName;

  head.appendChild(link);
}

addCss('{my-url}');
登入後複製

This code creates a new element with the specified href and appends it to the section.

Using jQuery:

function addCss(fileName) {
  $("<link />", {
    rel: "stylesheet",
    type: "text/css",
    href: fileName
  }).appendTo('head');
}

addCss("{my-url}");
登入後複製

Note: While it is technically possible to append the element to the section, it is not recommended as it violates the HTML specification. Therefore, it is preferable to append the element to the section for compliance and potential future browser compatibility issues.

以上是如何使用 JavaScript 從 Body 將樣式表注入 Head ?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板