宽度过渡顺风 CSS

Width transition tailwind CSS

我想显示并从页面左侧向右侧滑动一个元素。为此,我默认隐藏它。单击按钮时,将显示 ul 元素,其宽度从 0px 变为 100vw。我还在 ul 元素的宽度 属性 上添加了一个过渡。

HTML:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
  <button id="click_me" class="inline-block border-2 p-6"> Click Me! </button>
  <ul id="hidden_nav" class="hidden w-0 h-screen bg-red-50 mt-10 transition-[width] duration-1000">
    <li> Item </li>
    <li> Item </li>
  </ul>
</body>
</html>

JS:

const btn = document.getElementById('click_me');
const navul = document.getElementById('hidden_nav');
btn.addEventListener('click', function(){
  navul.classList.toggle('hidden');
  navul.classList.toggle('w-0');
  navul.classList.toggle('w-screen');
});

Codepen link:

https://codepen.io/Okumak/pen/qBVjwdY

然而,我看不到任何过渡正在进行,我也不明白为什么。

它永远不会与 hidden class 一起使用。另一种解决方案是 opacity.

const btn = document.getElementById('click_me');
const navul = document.getElementById('hidden_nav');
btn.addEventListener('click', function(){
  navul.classList.toggle('opacity-0');
  navul.classList.toggle('w-0');
  navul.classList.toggle('w-screen');
});
<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
  <button id="click_me" class="inline-block border-2 p-6"> Click Me! </button>
  <ul id="hidden_nav" class="opacity-0 w-0 h-screen bg-red-50 mt-10 transition-[width] duration-1000">
    <li> Item </li>
    <li> Item </li>
  </ul>
</body>
</html>

照顾height就好了。隐藏时它仍然占用 space,以防万一你也想切换它,那么你可以这样做。