簡體   English   中英

附加到html頁面腳本和CSS無效

[英]Appended to html page script and CSS don't work

我試圖將一些CSS和JS附加到我的靜態HTML文件中。 CSS和JS文件存儲在同一文件夾中。 這聽起來很愚蠢,但我需要這樣做。 因此,已添加CSS和JS,但由於背景應為紅色,因此它們不適用於HTML文件。 我創建的路徑是正確的,因為如果我inspect element了Chrome Devtools上的inspect element並單擊了附加鏈接,它將打開我需要的內容。 因此,沒有錯誤,腳本會附加我需要的內容,但是我看不到任何結果。

我的HTML檔案

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Home</title>
</head>
<body>

hello world

<script>
  const href = window.location.pathname;
  const chunkIndex = href.lastIndexOf('/');
  const path = href.slice(0, chunkIndex + 1);

  function appendScripts() {
    const script = document.createElement("script");
    script.src = path + "scripts.js";    // use this for linked script
    document.body.appendChild(script);
  }

  function appendCSS() {
    link=document.createElement('link');
    link.href= path + 'styles.css';
    link.rel='rel';
    document.getElementsByTagName('head')[0].appendChild(link);
  }

  document.addEventListener("DOMContentLoaded", function(event) {
    appendCSS();
    appendScripts();
  });
</script>

</body>
</html>

我的CSS文件:

body {
  background-color: red;
}

您需要修復以下行

link.rel='rel';

link.rel='stylesheet';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM