简体   繁体   中英

Javascript Onclick Button - Un-do an action on second click

sorry in advance if it's a noobish question I'm asking because I'm a newbie at Javascript.

Basically I've got a sidebar containing information hidden by overflow:hidden. I wanted to create a simple function: a button that onClick would change the values of the sidebar DIV to width:100%, height:100%, position:absolute. I did it no problems. However I hoped there was a way of making the button un-do and revert to original values on the second click, whatever the original values are , and I can't discover how to do it. Sound simple but I wonder if there's a way?

Thanks in advance and sorry again if it's a silly question.

在CSS中创建这些样式(例如,.extended类),并在需要时通过javascript添加/删除此类。

You can set a default style and then toggle another one on and off.

Since they are both classes, their specificity will be the same. In this case, the last class applied will go into effect and override the one applied earlier.

 // Get a reference to the button var btn = document.getElementById("btnToggle"); var sidebar = document.getElementById("sidebar"); // When the button is clicked, run an event handling function btn.addEventListener("click", function() { // Toggle the application of the "expanded" class. If it is not // currently being applied, apply it (overriding the previously // applied class of the same specificity). And, if it is currently // applied, then remove it (thus, restoring the rules from the default // class, which was never actually taken away). sidebar.classList.toggle("expanded"); }); 
 /* These properties/value apply to the side bar all the time. Notice that this selector is ID based, which gives it a specificity of 100 (very specific and hard to override). */ #sidebar { background: rgba(0,0,0,.3); height:100vh; position:absolute; bottom:0; right:0; padding:15px; } /* This class is initially applied in the HTML and only contains the properties/values that need to be overidden later. It has a specificity value of 10 */ .normal { width:5%; overflow:hidden; } /* This class will be added/removed via JavaScript. It also has a specificity value of 10 (ties with the .normal class), so when it is added, any property settings that conflict with earlier settings will override those earlier settings. And, when this class is removed, the earlier settings will no longer be overridden, so they will come back into effect. */ .expanded { width:25%; overflow:auto; } 
 <button id="btnToggle">Toggle Sidebar</button> <div id="sidebar" class="normal"> <h1>Side Bar</h1> <ul> <li>some content</li> <li>some content</li> <li>some content</li> </ul> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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