[英]How to use Javascript or Jquery to toggle the visibility of a html div
我正在创建一个基本站点,并且具有隐藏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()
});
})
演示: 小提琴
使用CSS:
<p style="display:none;">This is a test paragraph</p>
您有2个选项,像其他答案一样在html中设置css属性
<div id="description" style="display: none">
或将您的JavaScript包装在某种东西中,以告知页面在页面加载时运行Stript
使用jQuery
$(document).ready(function(){
//your code
});
要么
$(function(){
//your code
});
或常规的旧javascript
window.onload = function(){
//your code
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.