我现在正试图创建一系列按钮,让我的网站用户可以点击这些按钮来切换不同的CSS3文件,从而改变某些效果。为了实现这个目标,我需要一种访问HTML文档中标签的方法。
使用JavaScript或HTML。
href="example1.css"
标签在我的HTML中,将其更改为
href="example2.css"
使用JavaScript或HTML。
href="example1.css"
标签在我的HTML中,将其更改为
href="example2.css"
给你的链接分配一个id
。在JS中通过其id
获取,然后更改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";
getElementById
而不是getElementsById
,因为Id
应该是唯一的,因此只应该有一个。 - Andrei Bazanov不是
var link = document.getElementsById("lnk"); //Fetch the link by its ID
但是
link = document.getElementById("lnk");
这个ID是ONE,getElementsById - 是数组