使用JQuery切换div可见性 [英] Using JQuery to toggle div visibility

查看:99
本文介绍了使用JQuery切换div可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些jquery代码来切换Div的可见性。我按照这里发布的方法: http://jsfiddle.net/Ga7Jv/

I'm writing some jquery code to toggle a Div visibility. I followed the method posted here: http://jsfiddle.net/Ga7Jv/.

当用户点击图像(H2标签旁边)时,我希望它切换div。

When the user clicks an image (next to a H2 tag) i want it to toggle the div.

这是Jquery:

$(function()
{
$(".expander").live('click', function(){
        $(this).next("#TableData").slideDown();
        $(this).removeClass('expander');
        $(this).addClass('expanded');
});

$(".expanded").live('click', function(){
        $(this).next("#TableData").slideUp();
        $(this).removeClass('expanded');
        $(this).addClass('expander');
});

这是HTML:

<h3><img src="toggle.png" class ="expander" alt="Expand"/> 
Tabular Data</h3>
<div id="TableData">
//Content
</div>

将css应用于类扩展器,当我单击按钮时,看起来css会发生变化,正如我所料。所以我假设代码正在找到切换按钮并切换出正确的类。

The is css applied to the class expander and when i click the button it appears that the css changes, as i would expect. So i assume the code is finding the toggle button and switching out the classes alright.

然而它不执行我需要的动作,这是滑动div或者取决于该等级。

However it doesn't perform the action i need, which is to slide the div up or down depending on that class.

我尝试实现此目的的另一种方式是:

The other way i've tried to achieve this is with this:

  $(function(){
     $('.expander').live('click',function(){
     $('#TableData').show();
     $('#TableData').hide();
        });

这只关闭div并且当我点击它时不再打开。我也有它,所以它关闭很好但是当我打开它时它立即再次关闭。

This only closes the div and does not open again when i click it. I've also had it so it closes fine but when i open it, it immediately closes again.

谢谢

推荐答案

您的代码问题是它的最后一个函数调用是 .hide(),因此它将始终隐藏div

Problem with your code is that its last function call is .hide(), thus it will always hide the div

只需使用 .toggle() ,显示或隐藏t他匹配元素。

Simply use .toggle(), it display or hide the matched elements.

$(function(){
    $('.expander').live('click',function(){
        $('#TableData').toggle();
    });
});

小提琴

OR

$(function () {
    $('.expander').live('click', function () {
        $('#TableData').slideToggle();
    });
});

摆弄幻灯片

您可以使用 .slideToggle() ,如果要以滑动方式显示或隐藏匹配的元素

You can use .slideToggle(), if you want to display or hide the matched elements with a sliding motion

这篇关于使用JQuery切换div可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆