基本上我有一个包含溢出隐藏信息的侧边栏:隐藏。我想创建一个简单的函数:onClick的按钮会将侧边栏DIV的值更改为宽度:100%,高度:100%,位置:绝对。我没有遇到任何问题。但是我希望有一种方法可以让按钮取消操作并在第二次点击时恢复原始值,无论原始值,我都无法发现如何操作。听起来简单,但我想知道是否有办法?
如果这是一个愚蠢的问题,请提前致谢并再次抱歉。
答案 0 :(得分:4)
在css中创建这些样式(例如类.extended),并在需要时通过javascript添加/删除此类。
答案 1 :(得分:1)
您可以设置默认样式,然后打开和关闭 toggle 另一种样式。
由于它们都是类,因此它们的特异性是相同的。在这种情况下,应用的最后一个类将生效并覆盖之前应用的类。
// 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>