Div 可见性的过渡?

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

所以我有一个可以更改内容的分页,我希望内容的更改能够有一个过渡,但我不知道如何让它工作

let currentPage = 1;

function changeContent(page) {
  document.getElementById(`content${currentPage}`).classList.remove('active');
  currentPage = page;
  document.getElementById(`content${currentPage}`).classList.add('active');
}

// Zeige den ersten Inhalt beim Laden der Seite an
changeContent(currentPage);
body {
  font-family: Arial, sans-serif;
  margin : 20px;
  }
.content {
  display : none;
  }
.active {
  display : block;
  }
.pagination {
  margin-top : 20px;
  }
.pagination button {
  cursor  : pointer;
  padding : 10px;
  margin  : 5px;
  }
<div class="content" id="content1">
  <h2>Content 1</h2>
  <p>this is the first content</p>
</div>

<div class="content" id="content2">
  <h2>Content 2</h2>
  <p>this is the second content</p>
</div>

<div class="content" id="content3">
  <h2>Content 3</h2>
  <p>this is the third content</p>
</div>

<div class="pagination">
  <button onclick="changeContent(1)">1</button>
  <button onclick="changeContent(2)">2</button>
  <button onclick="changeContent(3)">3</button>
</div>

所以我希望它在“功能更改内容”功能上有一个平滑的过渡,例如屏幕上显示的内容之间的淡入淡出或其他内容,我在哪里添加过渡,我什至可以像我想象的那样简单地添加过渡?

javascript html css pagination
1个回答
0
投票

很抱歉,样式 z-index 和 display 不支持过渡,但是对于您的演示,有一个简单的方法可以实现相同的效果,那就是动画

<div class="content active" id="content1">
  <h2>Content 1</h2>
  <p>this is the first content</p>
</div>

<div class="content" id="content2">
  <h2>Content 2</h2>
  <p>this is the second content</p>
</div>

<div class="content" id="content3">
  <h2>Content 3</h2>
  <p>this is the third content</p>
</div>

<div class="pagination">
  <button onclick="changeContent(1)">1</button>
  <button onclick="changeContent(2)">2</button>
  <button onclick="changeContent(3)">3</button>
</div>
<script>
  let currentPage = 1;

  function changeContent(page) {
    document.getElementById(`content${currentPage}`).classList.remove('active');
    currentPage = page;
    document.getElementById(`content${currentPage}`).classList.add('active');
  }
</script>
<style>
  body {
    font-family: Arial, sans-serif;
    margin: 20px;
  }
  
  .content {
    display: none;
    animation: fade 2s ease-in;
  }
  
  .active {
    display: block;
  }
  
  .pagination {
    margin-top: 20px;
  }
  
  .pagination button {
    cursor: pointer;
    padding: 10px;
    margin: 5px;
  }
  
  @keyframes fade {
    0% {
      opacity: 0;
    }
    100% {
      opacity: 1;
    }
  }
</style>

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