CSS过渡的有害行为

时间:2018-09-13 23:00:48

标签: html css angular css-transitions

我有一个Angular应用程序。其 HTML 文件包含一个带有类行的div,该行本身包含两个带有div类的col。通过单击按钮,列的大小将更改:

<button class="btn btn-primay" (click)="changeColumnsSize()"> change column sizes</button>
      <div class="row">
        <div id="leftColumn" class="col-sm-{{leftColumnSize}}" style="background-color:lavender;">
          .col-sm-8     
        </div>
        <div id ="rightColumn" *ngIf="this.state===true" class="col-sm-{{rightColumnSize}}" style="background-color:lavenderblush;">
          .col-sm-4
        </div>
      </div>

要平滑调整大小,我在 CSS 文件的col类中添加了transition属性:

.col-sm-8 { transition: width .5s ease; }

.col-sm-4 { transition: width .5s ease ; }

TS 文件(包含changeColumnsSize函数)如下:

export class BoxComponent {
  leftColumnSize: number = 12;
  rightColumnSize: number = 0;
  colDifference: number = 4;
  state: boolean = false;

  constructor() { }

  changeColumnsSize(){
    if (this.state===false)
      this.state = true;
    else
      this.state = false;
    if(this.state===true) {
      this.leftColumnSize-=this.colDifference;
      this.rightColumnSize+=this.colDifference;
    }
    else if (this.state===false) {
      this.leftColumnSize+=this.colDifference;
      this.rightColumnSize-=this.colDifference;
     }
    }
  }

但是,有一个问题。每次发生转换时,rightColumn都会出现在leftColumn下方,然后向上移动到正确的位置。

您能帮我解决这个问题吗?我更喜欢在不使用Angular动画的情况下解决此问题。

1 个答案:

答案 0 :(得分:5)

这是因为在v4中,网格布局不是基于width属性(和盒子模型)而是基于
flex-basis + max-width(和flexbox模型)。

您需要在两个属性上都设置transition。或者,这是一种错误和错误的方式:在all上。

看到它正常工作:

function changeColSize() {
  $('.col-switcher > div').toggleClass('col-sm-4 col-sm-8')
}
.col-switcher>div {
  transition: max-width .3s cubic-bezier(.4, 0, .2, .1), 
              flex-basis .3s cubic-bezier(.4, 0, .2, .1);
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

<div class="container">
  <button class="btn btn-primay" onclick="changeColSize()"> change column sizes</button>
  <div class="row col-switcher">
    <div id="leftColumn" class="col-sm-8" style="background-color:lavender;">
      .col-sm-8
    </div>
    <div id="rightColumn" *ngIf="this.state===true" class="col-sm-4" style="background-color:lavenderblush;">
      .col-sm-4
    </div>
  </div>
</div>