Css 过渡固定宽度与最大宽度

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

我有两个例子。第一个固定宽度为 400px 并随过渡扩展,第二个具有最大宽度且不随过渡扩展。但是,如果我在转换前检查 offsetWidth,它们都会返回 400。

我怎样才能让第二个随着过渡而扩展?

document.getElementById('t').addEventListener('click', function() {
  console.log(document.querySelector('.plan').offsetWidth)
  document.querySelector('.plan').classList.add('expanded')
})

document.getElementById('t2').addEventListener('click', function() {
  console.log(document.querySelector('.plan').offsetWidth)
  document.querySelector('.plan2').classList.add('expanded')
})
.plan {
  width: 400px;
  position: relative;
  top: 0;
  left: 0;
  transition: width 0.3s ease-out, height 0.3s ease-out;
  height: 100px;
  background: red;
}

.plan2 {
  max-width: 400px;
  width: 100%;
  position: relative;
  top: 0;
  left: 0;
  transition: width 0.3s ease-out, height 0.3s ease-out;
  height: 100px;
  background: red;
}

.expanded {
  width: 100%;
  max-width: none;
}
<div class="plan"></div>

<a href="#" id="t">expand</a>

<div class="plan2"></div>

<a href="#" id="t2">expand 2</a>

javascript html css css-transitions
1个回答
0
投票

对于

max-width: 100%
类,您可以使用
none
代替
.expanded

document.getElementById('t').addEventListener('click', function() {
  console.log(document.querySelector('.plan').offsetWidth)
  document.querySelector('.plan').classList.add('expanded')
})

document.getElementById('t2').addEventListener('click', function() {
  console.log(document.querySelector('.plan').offsetWidth)
  document.querySelector('.plan2').classList.add('expanded')
})
.plan {
  width: 400px;
  position: relative;
  top: 0;
  left: 0;
  transition: width 0.3s ease-out, height 0.3s ease-out;
  height: 100px;
  background: red;
}

.plan2 {
  max-width: 400px;
  width: 100%;
  position: relative;
  top: 0;
  left: 0;
  transition: max-width 0.3s ease-out, height 0.3s ease-out;
  height: 100px;
  background: red;
}

.expanded {
  width: 100%;
  max-width: 100%;
}
<div class="plan"></div>

<a href="#" id="t">expand</a>

<div class="plan2"></div>

<a href="#" id="t2">expand 2</a>

© www.soinside.com 2019 - 2024. All rights reserved.