【问题标题】:is it possible to change CSS with JavaScript? [duplicate]是否可以使用 JavaScript 更改 CSS? [复制]
【发布时间】:2021-06-30 04:33:39
【问题描述】:

我正在尝试添加“过滤器:模糊 5px;”单击某个按钮时影响 CSS 到 Id。我想知道如何在按下按钮时使用 JavaScript eventListener 或类似的东西更改 CSS。

【问题讨论】:

  • button.style.filter = 'blur 5px';
  • 在元素上切换一个类......
  • 您可以添加一个函数并在单击时调用它或在单击事件时切换类。

标签: javascript css


【解决方案1】:

您可以通过选择您希望应用样式的 DOM 元素,然后在事件侦听器中将所需样式添加到选定的 DOM 元素来实现。您还可以切换应用于 DOM 元素的类。检查下面的代码sn-p:

const btn = document.querySelector("#btn");
const text = document.querySelector("#text");

const btn2 = document.querySelector("#btn2");
const text2 = document.querySelector("#text2");

btn.addEventListener("click", (e) => {
  text.style.filter = `blur(3px)`
});

// Or you can toggle a class on the text element
btn2.addEventListener("click", () => {
  text2.classList.toggle("blur");
});
.blur {
 filter: blur(3px);
}
<div id="text">Hope! This answer is useful</div>
<button id="btn">Blurs the text above</button>

<div id="text2">Thanks for upvoting ;)</div>
<button id="btn2">Toggles blur class on the text above</button>

【讨论】:

    【解决方案2】:

    let
    button =document.getElementById("btn");
    div = document.getElementById("div");
    button.onclick = function blur(){
    
        div.style.filter = `blur(5px)`
    }
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
    <title>index</title>
    
    
    </head>
    <body>
        <div id="div"><h1>hello world</h1> </div>
        <button id="btn"> add blur</button>
    
    <script src="test.js"></script>
    </body>
    </html>

    【讨论】:

    • 谢谢!这解决了我的问题。
    【解决方案3】:

    JavaScript 在HTMLElements 上提供了一个style 属性。

    就像获取元素一样简单(关于 here 的教程)。

    例子:

    const btn = document.querySelector("#id-of-button");
    

    然后,(如果该元素存在),您可以像这样访问样式属性:

    btn.style = "filter: blur(5px);";
    

    另外,如果你想要重置样式属性,你可以像这样得到你想要改变的特定样式:

    btn.style.filter = "blur(5px)";
    

    请注意,您不必在末尾添加分号(如果这样做实际上将不起作用)。

    此外,在 CSS 中用 em-dashes 分隔的元素样式属性(如 flex-direction,以驼峰形式编写,如:btn.style.flexDirection)。

    您可以使用addEventListener 函数添加事件监听器:

    btn.addEventListener("click", function(event){
      btn.style.filter = "blur(5px)";
    });
    

    您可以使用传递给函数的event 参数来获取有关事件的更多信息,例如触发事件、点击类型(右键或左键)等

    编辑:

    我忘了注意您想在单击按钮时更改另一个元素的样式。

    为此,您只需将事件侦听器更改为:

    btn.addEventListener("click", function(event){
      document.querySelector("#id-of-div").style.filter = "blur(5px)";
    });
    

    【讨论】:

    • 感谢您的评论!以及不同的方式来做到这一点我很感激
    猜你喜欢
    • 2013-04-21
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 2013-11-17
    • 2013-07-16
    相关资源
    最近更新 更多