Joh*_*ohn 43 html javascript jquery toggle
我有一些代码显示三个图像和每个图像下的相应div.使用jquery .toggle函数,我已经使它成为每个div在单击它上面的图像时切换.是否有任何方法可以让div开始隐藏?
感谢您的时间,
参考代码:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#picOne").click(function(){
$("#one").toggle(250);
});
$("#picTwo").click(function(){
$("#two").toggle(250);
});
$("#picThree").click(function(){
$("#three").toggle(250);
});
});
</script>
</head>
<body>
<center>
<h2>Smooth Transitions</h2>
<img src="one.png" id="picOne">
<div id="one">
<p>first paragraph.</p>
</div>
<img src="two.png" id="picTwo">
<div id="two" visibility="hidden">
<p>Second Pair of giraffe.</p>
</div>
<img src="three.png" id="picThree">
<div id="three">
<p>Thiird paragraph.</p>
</div>
</center>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
Ada*_*kis 63
visibility是一个css属性.但无论如何,显示都是你想要的
<div id="two" style="display:none;">
<p>Second Pair of giraffe.</p>
</div>
Run Code Online (Sandbox Code Playgroud)
或者抛弃内联css并给每个div切换一个css类
<div id="two" class="initiallyHidden">
Run Code Online (Sandbox Code Playgroud)
然后
.initiallyHidden { display: none; }
Run Code Online (Sandbox Code Playgroud)
你也可以稍微清理你的jQuery.将您的切换触发图像作为css类
<img src="one.png" class="toggler">
<div>
<p>first paragraph.</p>
</div>
Run Code Online (Sandbox Code Playgroud)
然后
$("img.toggler").click(function(){
$(this).next().toggle(250);
});
Run Code Online (Sandbox Code Playgroud)
这样可以避免您对所有这些ID的需求,并且还可以使这个解决方案变得更加可扩展.
要处理动态添加的内容,您可以使用on而不是click
$(document).on("click", "img.toggler", function(){
$(this).next().toggle(250);
});
Run Code Online (Sandbox Code Playgroud)
(为了获得更好的性能,请确保所有这些切换图像都在某个容器div中,例如,命名containerFoo,然后执行,$("#containerFoo").on而不是$(document).on(
用css:
#one, #two, #three { display: none; }
Run Code Online (Sandbox Code Playgroud)
用jQuery
$(function() { //once the document is ready
$('h2').nextAll('img') //select all imgs following the h2
.find('div') //select all contained divs
.hide();
})
Run Code Online (Sandbox Code Playgroud)
顺便说一下,您应该使用类,而不是使用id选择器
| 归档时间: |
|
| 查看次数: |
62968 次 |
| 最近记录: |