頁面結構
<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>