前端杂记(二)jquery实现元素隐藏的四个方法(附测试代码)

页面结构

<div>
    <h2>title</h2>
    <input type="button" value="click"/>
</div>

四种方法

  • $('h2').hide()$('h2').show() – 常用方法
  • $('h2').attr('hidden','')$('h2').removeAttr('hidden')
  • $('h2').css('display','none')$('h2').css('display','block') – 备用实现
  • $('h2').attr('style','display:none')$('h2').removeAttr('style')

What’s More

$.hide() => element.style.display = 'none'
$.show() => element.style.display = getDefaultDisplay(elem)
长时间使用发现上述方法容易记混,整理此贴供查阅
上述方法只是简单赋予display样式,实际场景中常使用toggleClass(addClass/removeClass)做样式补充

测试代码

使用方法:将上面代码复制替换到注解行

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="static/jquery-3.2.1.js"></script>
    <script>
        function hideTitle(jqTitle){
            //hideCode
            console.log('hide');
        }
        function showTitle(jqTitle){
            //showCode
            console.log('show');
        }
        $(document).ready(function(){
            var jqTitle = $('h2');
            $('input').click(function(){
                if(jqTitle.is(':visible')){
                    hideTitle();
                }else{
                    showTitle();
                }
            })
        })
    </script>
</head>
<body>
<div>
    <h2>title</h2>
    <input type="button" value="click"/>
</div>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/bkk854762363/article/details/79192692
今日推荐