div从右向全角滑动

问题描述 投票:1回答:3

[目前,我正在构建样式指南,并且对元素的过渡有疑问。想象一下,您有一个容器,其中两个元素彼此分开。两者的宽度均为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添加哪个?

javascript html css
3个回答
1
投票

尝试使用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>

0
投票

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

.module-container {
  display: flex;
  height: 50px;
}

.module-container:hover .second-element {
  margin-left: 0;
}

.first-element {
  flex: 0 0 50%;
  background: #f90;
  position: relative;
}

.second-element {
  flex: 0 0 50%;
  background: #0f9;
  margin-left: -50%;
  transition: all .6s ease;
}
<div class="module-container">
  <div class="first-element"></div>
  <div class="second-element"></div>
</div>

或者您可以使用position: absolute并为left属性设置动画

.module-container {
  position: relative;
  height: 50px;
}

.module-container:hover .second-element {
  left: 50%;
}

.first-element {
  width: 50%;
  background: #f90;
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  z-index: 1;
}

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

0
投票

.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>
© www.soinside.com 2019 - 2024. All rights reserved.