如何用javascript改变css href =""?

use*_*656 6 javascript css

我想用js改变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>
Run Code Online (Sandbox Code Playgroud)

我必须修复上面的代码.

<link rel="stylesheet" href="u1.css" type="text/css" />
Run Code Online (Sandbox Code Playgroud)

变成

<link rel="stylesheet" href="u2.css" type="text/css" />
Run Code Online (Sandbox Code Playgroud)

我可以在head标签中更改css href吗?可能吗?

Sam*_*son 9

像使用document.querySelector或使用任何其他元素一样查询它document.querySelectorAll.

document.querySelector("link[href='u1.css']").href = "u2.css";
Run Code Online (Sandbox Code Playgroud)

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

举个例子:

// Change [href] on first stylesheet to u2.css
document.styleSheets[0].href = "u2.css";
Run Code Online (Sandbox Code Playgroud)

  • 根据我的经验,浏览器会忽略诸如`document.styleSheets[0].href = "u2.css";`之类的内容...您是否必须采取措施才能在此类页面上关闭浏览器安全性?或者也许现代浏览器根本不再允许它。 (2认同)