我正在创建一个基本网站,并且我有以下隐藏 div 的脚本:
<script type="text/javascript">
<!--
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//-->
</script>
<a href="#" onclick="toggle_visibility('description');">Show/Hide Description</a>
<div id="description">
<br>
<br>
<p>This is a test paragraph</p>
</div>
当我加载页面时,默认显示文本。如何在每次加载页面时隐藏 div 内的文本?
我希望用户手动单击按钮来查看文本。
编辑:
我现在添加了 + 符号的图片,以便用户可以单击 +,并使用以下行显示文本:
<h4>Backstory</h4>
<img alt="" style="width: 20px; height: 20px;" src="./images/headerExpand.png" a href="#" onclick="toggle_visibility('backstory');">Show/Hide Description</a>
<div id="backstory" style="display: none">
<br>
<p>This is a new block of text</p>
</div>
./images/headerExpand.png 是 + 符号的图标
单击 + 图标后,如何将 + 图标更改为 - 图标?
谢谢。
最佳答案
将显示设置为无
<div id="description" style="display: none">
<小时/>
重新设计的解决方案可能看起来像
<!-- Add a class toggler and the id of the target element as the href-->
<a href="#description" class="toggler">Show/Hide Description</a>
<!-- Add a class hidden so that the element is hidden when the page loads -->
<div id="description" class="hidden">
<br/>
<br/>
<p>This is a test paragraph</p>
</div>
CSS
.hidden {
display: none;
}
然后是 jQuery 脚本
// dom ready handler
jQuery(function () {
//register a click handelr for all anchor elements with class toggler
$('a.toggler').click(function (e) {
//prevent the default action of the event
e.preventDefault();
//togger the visibility of the element targetted by the href
$($(this).attr('href')).toggle()
});
})
演示:Fiddle
关于javascript - 如何使用 Javascript 或 Jquery 切换 html div 的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20886102/