您的位置:首页 > Web前端 > JQuery

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

2018-01-29 11:35 435 查看

页面结构

<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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jquery