簡體   English   中英

Javascript Onclick按鈕-再次單擊時不執行操作

[英]Javascript Onclick Button - Un-do an action on second click

如果我要問的是一個討厭的問題,請先抱歉,因為我是Javascript的新手。

基本上,我有一個側邊欄,其中包含由overflow:hidden隱藏的信息。 我想創建一個簡單的函數:一個onClick可以將側欄DIV的值更改為width:100%,height:100%,position:absolute的按鈕。 我沒問題。 但是我希望有一種方法可以使該按鈕撤消並在第二次單擊時恢復為原始值, 無論原始值是什么 ,我都無法找到如何做的方法。 聽起來很簡單,但我想知道是否有辦法?

在此先謝謝您,如果這是一個愚蠢的問題,請再次抱歉。

在CSS中創建這些樣式(例如,.extended類),並在需要時通過javascript添加/刪除此類。

您可以設置一個默認的樣式,然后切換和關閉另一個。

由於它們都是類,因此它們的特異性相同。 在這種情況下,最后一個應用的類將生效並覆蓋之前應用的一個類。

 // 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM