CSS實現隨機標簽展示
#random-tags { display: flex; flex-wrap: wrap; } .tag { background-color: #f2f2f2; border-radius: 0.3rem; padding: 0.5rem; margin: 0.5rem; font-size: 0.7rem; } .tag:nth-of-type(1) { background-color: #ffcc66; } .tag:nth-of-type(2) { background-color: #0099cc; } .tag:nth-of-type(3) { background-color: #ff6666; } .tag:nth-of-type(4) { background-color: #33cc99; } .tag:nth-of-type(5) { background-color: #9966cc; }
CSS的偽類nth-of-type()可以獲得標簽的序列號,我們可以利用這個特性來隨機展示標簽。例如,如果我們想要隨機展示5個標簽,我們可以在CSS中給這5個標簽添加對應的序列號,然后在JavaScript中隨機生成一個1-5的整數,通過nth-of-type()將對應序列號的標簽顯示出來。
// 獲取所有標簽 const tags = document.querySelectorAll('.tag'); // 隨機生成1-5的整數 const randomIndex = Math.floor(Math.random() * 5) + 1; // 根據隨機索引顯示對應的標簽 document.querySelector(`.tag:nth-of-type(${randomIndex})`).style.display = 'block';
為了讓標簽隨機展示,我們還可以通過CSS的flex布局,將所有標簽包裹在一個容器中,實現標簽的自動排列和換行。
標簽1標簽2標簽3標簽4標簽5
以上是實現隨機標簽展示的完整代碼,通過簡單的CSS和JavaScript結合,我們可以輕松實現這種有趣的效果,為網頁增加一些趣味性和交互性。
上一篇css實現黑板樣式
下一篇css實現黑色透明罩