1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS隐藏和显示元素示例</title> <style> .hidden { display: none; } .visible { display: block; } button { margin-top: 10px; } </style> </head> <body>
<div>这是一个始终显示的元素</div> <div class="hidden">这是一个默认隐藏的元素</div>
<button onclick="toggleElement()">切换元素显示/隐藏</button>
<script> function toggleElement() { var element = document.querySelector('.hidden'); if (element.classList.contains('hidden')) { element.classList.remove('hidden'); element.classList.add('visible'); } else { element.classList.remove('visible'); element.classList.add('hidden'); } } </script>
</body> </html>
|