[英]How do I bind style to onclick element using Javascript?
Whenever I click on the left arrow icon, I want the style of the menu to change.每当我单击左箭头图标时,我都希望更改菜单的样式。 Is it possible to bind specific css style when using onclick function?
使用 onclick function 时是否可以绑定特定的 css 样式?
i.fas.fa-chevron-circle-left.left
#sidebar-container .menu
width: 18rem
transition: 200ms
How I want it to look after onclick function.我希望它如何照顾 onclick function。
#sidebar-container .menu
width: 10rem
Make a class containing the styles you want and you can toggle those on and off using javascript:制作一个包含您想要的 styles 的 class,您可以使用 javascript 打开和关闭它们:
document.getElementById('my-element').classList.toggle('my-class');
This will add the my-class
class if the element doesnt have it, and remove the my-class
class if the element does have it.如果元素没有它,这将添加
my-class
class,如果元素有它,则删除my-class
class。 You may also use classList.add
and classList.remove
if you'd like to set it on or off.如果您想打开或关闭它,您也可以使用
classList.add
和classList.remove
。
You can easily bind this to a button with inline javascript.您可以轻松地将其绑定到具有内联 javascript 的按钮。 It is recomended to use event listeners but this should do the trick:
建议使用事件侦听器,但这应该可以解决问题:
<button onclick="document.getElementById('my-element').classList.toggle('my-class')">Click me to toggle the class</button>
You can change my-elemment
to be the ID of the element you want to toggle the class for and my-class
to the classname you'd like to use.您可以将
my-elemment
element 更改为要切换 class 的元素的 ID,并将my-class
更改为您想要使用的类名。
It is possible to bind to an element.可以绑定到元素。 You can use document.querySelector() to find that element.
您可以使用 document.querySelector() 来查找该元素。
for example:例如:
const el = document.querySelector("i.fas.fa-chevron-circle-left.left")
el.addEventListener("click", function(){
el.style.transition = "";
});
It's almost always easier to just add an overriding class instead of editing single style properties:添加覆盖 class 而不是编辑单一样式属性几乎总是更容易:
el.classList.add("override");
and have that class in css somewhere.并在 css 某处拥有 class 。
.override {
transition: none !important;
}
You can create a secondary class for styles you want when it is clicked.您可以在单击时为您想要的 styles 创建一个辅助 class。 You can toggle the class like this
您可以像这样切换 class
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>
Hope it helps.希望能帮助到你。 Cheers!
干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.