<html lang="en"> <head> <meta charset="UTF-8"> <title>标签或者内容的隐藏</title> <style> .display-none{ display:none; } .display-block{ display:inline-block; } /* visibility属性 */ .visibility-hidden{ visibility:hidden; } .visibility-visible{ visibility:visible; } </style> </head> <body> <h3>1.hidden属性</h3> <span id="hidden" hidden>通过hidden属性显示或隐藏</span> <span style="width:30px;height:30px;background-color:pink;" onclick="fnHidden()">hidden属性--点击</span> <h3>2.style的display属性</h3> <span id="display" class="display-none">通过display属性显示或者隐藏</span> <span style="width:30px;height:30px;background-color:pink;" onclick="fndDisplay()">display属性--点击</span> <h3>2.style的display属性</h3> <span id="visibility" class="visibility-hidden">visibility属性显示或者隐藏</span> <span style="width:30px;height:30px;background-color:pink;" onclick="fnVisibility()">visibility属性--点击</span> <h2 style="color:red;">总结</h2> 方式1和方式2:隐藏元素不会占位置;<br/> 方式3,隐藏元素依旧占位子,避免空出位置。 </body> <script type="text/javascript"> /** *hidden属性应用 --方式1 */ function fnHidden(){ var ele = document.getElementById(‘hidden‘); var flag = ele.hasAttribute(‘hidden‘);//是否有hidden属性 if(flag){//隐藏 ele.removeAttribute(‘hidden‘); }else{//显示 ele.setAttribute(‘hidden‘,‘hidden‘); } } /** *display属性--方式1 */ function fndDisplay(){ var ele = document.getElementById(‘display‘); var className = ele.className; if(className == ‘display-none‘){//隐藏 ele.className = ‘display-block‘ }else{//显示 ele.className = ‘display-none‘ } } /** *visibility属性--方式3 */ function fnVisibility(){ var ele = document.getElementById(‘visibility‘); var className = ele.className; if(className == ‘visibility-hidden‘){//隐藏 ele.className = ‘visibility-visible‘ }else{//显示 ele.className = ‘visibility-hidden‘ } } </script> </html>