如何使用JavaScript更改CSS中的href=""?

11

我想使用 JavaScript 更改 CSS 的 href。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org  /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ko" xml:lang="ko">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title> New Document </title>
    <link rel="stylesheet" href="u1.css" type="text/css" />
</head>

我需要修复上面的代码。

<link rel="stylesheet" href="u1.css" type="text/css" />

变成

<link rel="stylesheet" href="u2.css" type="text/css" />

我可以更改标签中的CSS链接吗?这是可能的吗?

2个回答

16

像查询其他元素一样使用document.querySelectordocument.querySelectorAll来查询它。

document.querySelector("link[href='u1.css']").href = "u2.css";

或者,您也可以通过document.styleSheets访问它。

例如:

// Change [href] on first stylesheet to u2.css
document.styleSheets[0].href = "u2.css";

2
根据我的经验,浏览器会忽略类似 document.styleSheets[0].href = "u2.css"; 的代码...你需要在这样的页面上降低浏览器安全性吗?或者现代浏览器可能已不再支持此功能。 - Troy

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接