使用CSS/Javascript将侧边栏div与另一个div切换 [英] Toggle sidebar div with another div using CSS/Javascript
问题描述
这是我的情况:
因此,我试图通过单击另一个div来切换侧边栏.这是一个固定在视口右侧的高度为100%的侧边栏.本质上,我正在尝试将50px宽的切换div和250px宽的侧边栏div都包裹一个300px的div,并且我想使用负的margin-right像素值来隐藏侧边栏部分.使用.toggle:active选择器(因此,在单击切换div时会发生这种情况),我想通过将右边距右边的像素值设置回0px来显示侧边栏部分.
So I'm trying to toggle a sidebar by clicking another div. It's a 100% height sidebar that is fixed to the right side of the viewport. Essentially I am trying to wrap a 300px div around both the 50px wide toggle div and the 250px wide sidebar div, and I want to hide the sidebar portion using a negative margin-right pixel value. Using the .toggle:active selector (so this occurs when the toggle div is clicked), I want to show the sidebar portion by setting that margin-right pixel value back to 0px.
到目前为止的代码:
<div class="wrapper">
<a href="#">
<div class="toggle">Toggle</div>
</a>
<div class="cart">Cart</div>
</div>
到目前为止的
CSS:
CSS so far:
.wrapper {
position:fixed;
width:300px;
height:100%;
background-color:orange;
top:0;
right:0;
margin-right:-250px;
}
.toggle {
position:relative;
display:block;
width:50px;
height:100%;
background-color:grey;
float:left;
}
.toggle:active .wrapper {
margin-right:0px;
}
.cart {
position: relative;
width:250px;
height:100%;
background-color:red;
float:right;
}
这是我的问题:
在启用.toggle:active时,如何定位.wrapper来更改css属性?另外,如何指定边栏何时可见以及何时不可见?
How can I target .wrapper to change a css attribute when .toggle:active is engaged? Also, how can I specify when the sidebar is visible and when it's not?
我是Java语言的新手,但是由于回调函数的缘故,我似乎需要它来执行此操作.如果仅CSS可行,那么我会倾向于该解决方案.请注意,我要使用margin-right,以便以后可以选择使用CSS过渡为左右滑动的元素设置动画.
I'm new to Javascript, but it seems like I'll need it to do this due to the callback function. If CSS-only is possible, I'd lean toward that solution. Please note that I want to use margin-right so that I can opt to use CSS transitions later to animate my element sliding left and right.
推荐答案
我建议为此使用jQuery.这很简单,出错的机会更少.
I would recommend using jQuery for this. It is simple and less chance for errors.
$('.toggle').click(function() {
$('.cart').toggle();
});
这篇关于使用CSS/Javascript将侧边栏div与另一个div切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!