如何使用JavaScript将样式绑定到onclick元素?

问题描述

每当我单击左箭头图标时,我都希望菜单样式发生变化。使用onclick函数时是否可以绑定特定的CSS样式?

i.fas.fa-chevron-circle-left.left

#sidebar-container .menu
  width: 18rem
  transition: 200ms

我希望它如何处理onclick函数。

#sidebar-container .menu
  width: 10rem
  

解决方法

制作一个包含所需样式的类,您可以使用javascript启用和禁用这些样式:

document.getElementById('my-element').classList.toggle('my-class');

如果元素没有my-class类,它将添加my-class类;如果元素没有它,则将删除classList.add类。如果您想将其设置为打开或关闭,也可以使用classList.remove<button onclick="document.getElementById('my-element').classList.toggle('my-class')">Click me to toggle the class</button>

您可以使用内嵌javascript将其轻松绑定到按钮。建议使用事件侦听器,但这应该可以解决问题:

my-elemment

您可以将my-class更改为您要为其切换类的元素的ID,并将element = driver.find_element_by_link_text("Download") 更改为您要使用的类名。

,

可以绑定到元素。您可以使用document.querySelector()查找该元素。

例如:

el.classList.add("override");

添加覆盖类而不是编辑单个样式属性几乎总是更容易:

.override {
    transition: none !important;
}

并将该类放在CSS中的某个地方。

{{1}}
,

您可以为单击时想要的样式创建辅助类。您可以像这样切换课程

const menu = document.querySelector("#sidebar-container .menu");

menu.addEventListener('click',function () {
// by adding class name
  menu.classList.toggle("menu-clicked");
});
#sidebar-container {
  width: 200px;
  height: 100vh;
  background: #ccc;
  display: flex;
  padding-top: 20px;
  align-items: flex-start;
  justify-content: center;
  transition: all ease 200ms;
}

#sidebar-container .menu {
  background: #ddd;
  padding: 20px;
  display: block;
  width: 100%;
  cursor: pointer;
}

#sidebar-container .menu.menu-clicked {
  background: green;
}
<div id="sidebar-container">
  <div class="menu">
    Menu
  </div>
</div>

希望有帮助。干杯!

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...