div 从右边滑动到全宽



目前,我正在构建一个风格指南,我有一个关于元素过渡的问题。假设您有一个容器,其中包含两个彼此相邻的元素。两者都有 50% 的宽度。左侧元素应始终可见,但右侧元素从右侧滑动到 50% 的宽度。我怎样才能实现这样的事情?我对顶部,底部,左侧,右侧,位置:绝对属性有点不知所措。

html 看起来像这样:

<div class="module-container">
<div class="first-element">
<div class="second-element">
</div>

CSS是这样的:

.module-container {
display: flex;
}
.first-element {
width: 50%;
}
.second-element {
width: 50%;
}

第二个元素首先需要哪些属性?例如,在按下按钮后,我应该通过JavaScript添加哪些内容?

尝试使用jQuery和转换

$('#btn').click(function() {
$('.secondElement').toggleClass("slide");
});
.moduleContainer {
display: flex;
height: 100px;
overflow: hidden;
}
.firstElement {
position: relative;
width: 50%;
border: 1px solid #000;
}
.secondElement {
position: relative;
width: 50%;
border: 1px solid #000;
left: 100%;
transition: left 1s;
}
.secondElement.slide {
left: 0;
}
#btn {
display: block;
margin-top: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="moduleContainer">
<div class="firstElement"></div>
<div class="secondElement"></div>
</div>
<button id="btn">Click Here</button>

.moduleContainer {
display: flex;
height:100px;
}
.moduleContainer > * {
border:1px solid red;
box-sizing:border-box;
overflow:hidden;
}
.firstElement {
height: 100%;
width: 50%;
}
.secondElement {
height: 100%;
width: 0%;
transition:width 0.3s ease;
}
.moduleContainer:hover .secondElement {
width:50%;
}
<div class="moduleContainer">
<div class="firstElement"></div>
<div class="secondElement"></div>
</div>

我已经用纯CSS实现了它。我认为有一个栏很好,这样用户就可以悬停它并展开。我希望它能帮助你。

.moduleContainer{ display: flex;flex-flow: row nowrap; }
.firstElement{ background-color:blueviolet;flex:1;height:100px;position:relative;max-width: 50%;  }

.secondElement{ background-color:aqua;height:100px;flex:1;max-width:1%;position:relative;transition:1s ease;left:48%;  }
.secondElement:hover{ background-color: chartreuse;left:0px;max-width:50%; }
<div class="moduleContainer">
<div class="firstElement">First Element</div>
<div class="secondElement"></div>
</div>

您可以对margin-left.second-element使用负值。

.module-container {
display: flex;
height: 50px;
overflow: hidden;
}
.module-container:hover .second-element {
right: 0;
}
.first-element {
flex: 0 0 50%;
background: #f90;
}
.second-element {
flex: 0 0 50%;
background: #0f9;
right: -50%;
transition: all .6s ease;
position: relative;
}
<div class="module-container">
<div class="first-element"></div>
<div class="second-element"></div>
</div>

或者,您可以使用position: absolute并对left属性进行动画处理

.module-container {
position: relative;
height: 50px;
overflow: hidden;
}
.module-container:hover .second-element {
right: 0;
}
.first-element {
width: 50%;
background: #f90;
position: absolute;
left: 0;
top: 0;
bottom: 0;
}
.second-element {
background: #0f9;
width: 50%;
position: absolute;
right: -50%;
top: 0;
bottom: 0;
transition: all .6s ease;
}
<div class="module-container">
<div class="first-element"></div>
<div class="second-element"></div>
</div>

最新更新