简体   繁体   English

如何通过 javascript 更改 `link` 中的 `href`

[英]how to change `href` in `link` by javascript

I would like to change target on link tag with my css.我想用我的 css 更改link标签上的target I would like to do this with javascript.我想用 javascript 来做这件事。 It should be when I click on button.它应该是当我点击按钮时。 I have html file我有 html 文件

<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

    <link rel="stylesheet" href="css/general.css">
    <link id="my_css" rel="stylesheet" href="css/normal_mode.css">


</head>
<body id="my_body">
...

I have javascript file我有 javascript 文件

function dark_mode() 
    {
        if(document.getElementById("my_css").href == "css/normal_mode.css")
        {
            document.getElementById("my_body").className = ""; 
            document.getElementById("my_name").className = "";
            document.getElementById("my_css").href = "new.css";
...

Your approach is incorrect, or not practical.您的方法不正确或不实用。 What you need to do is to load CSS for both themes and change the body theme data or class.您需要做的是为两个主题加载 CSS 并更改主体主题数据或 class。

.theme-dark {
  --bg: black;
  --text: white;
}

.theme-light {
    --bg: white;
    --text: black;
}

in JS在 JS 中

document.querySelector(".switch-theme").addEventListener("click", () => {
   document.body.classList.toggle("theme-dark");
   document.body.classList.toggle("theme-light");
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM