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)";
});