[英]CSS-Javascript: Show and Hide div
我想創建一個菜單,其中僅包含標題,並提供查看更多鏈接。 如果單擊該鏈接,則應打開一個隱藏的div,並且該視圖應更改為更少或關閉。 如果我單擊該div,則應再次關閉。 到目前為止,我有這個。
Title 1 <a href="#" onclick="showdiv()">View More</a>
<div id="title1_div">
Some Information
</div>
<style>
#title1_div{
display:none;
}
</style>
<script>
function showdiv()
{
document.getElementById('title1_div').style.display = 'block';
}
</script>
這僅提供點擊顯示分區。 單擊如何關閉該div。
任何幫助,將不勝感激。
請在JSFiddle上查看以下示例: https ://jsfiddle.net/eo4cysec/
您只需檢查該屬性是否設置為阻止,如果設置為無,則將其設置為阻止。 因此,您具有切換邏輯。
if(document.getElementById('title1').style.display == 'block') {
document.getElementById('title1').style.display = 'none';
} else {
document.getElementById('title1').style.display = 'block';
}
要將文本設置為View Less ,需要引用click標記,將其作為參數傳遞,如下所示:
<a href="#" onclick="showdiv(this)">View More</a>
然后,您將有機會使用此參數並設置它的innerHTML
,即顯示的文本。 因此最終函數將如下所示,其中e
現在a
-tag上的引用:
function showdiv(e) {
if(document.getElementById('title1').style.display == 'block') {
e.innerHTML = 'View More';
document.getElementById('title1').style.display = 'none';
} else {
e.innerHTML = 'View Less';
document.getElementById('title1').style.display = 'block';
}
}
請查看此小提琴:
功能簡單。 單擊以調用它,它將處理隱藏/顯示:
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
這是一個工作示例。
function showdiv(el) { if (el.innerHTML == "View More") { document.getElementById('title1').style.display = 'block'; el.innerHTML = "Show Less"; } else { document.getElementById('title1').style.display = 'none'; el.innerHTML = "View More"; } }
#title1 { display: none; }
Title 1 <div id="title1"> Some Information </div> <a href="#" onclick="showdiv(this)">View More</a>
$('a').click(function () {
$(this).next('div').stop(true, true).slideToggle("fast");
if($(this).html() == 'View More'){
$(this).html('View Less');
} else {
$(this).html('View More');
}
}),
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.