【问题标题】:Switching between multiple CSS files using Javascript使用 Javascript 在多个 CSS 文件之间切换
【发布时间】:2015-05-22 16:41:01
【问题描述】:

我目前正在尝试制作一系列按钮,我的网站的用户可以点击这些按钮,以便在不同的 CSS3 文件之间进行切换,这将改变某些效果。为了实现这个目标,我需要某种方式来访问

href="example1.css"

在我的 HTML 中添加标签,并将其更改为

href="example2.css" 

使用 JavaScript 或 HTML。

【问题讨论】:

标签: javascript html css


【解决方案1】:

id 分配给您的链接。通过 id 在 JS 中获取它并更改 href 属性。

<link rel="stylesheet" type="text/css" href="example1.css" id="lnk"/>

在 JS 中:

var link = document.getElementsById("lnk"); //Fetch the link by its ID
link.setAttribute("href", "example2.css"); //Change its href attribute

您也可以不使用id

document.querySelector("link[href='example1.css']").href = "example2.css";

【讨论】:

  • 拼写错误。 getElementsById 应该是 getElementById 因为真的,Id 应该是唯一的,因此应该只有一个。
【解决方案2】:

不是

var link = document.getElementsById("lnk"); //Fetch the link by its ID 

但是

link = document.getElementById("lnk"); 

ID 为 ONE,getElementsById - 为数组

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 2023-03-07
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    • 2019-07-08
    • 2022-12-25
    相关资源
    最近更新 更多