Javascript切换隐藏

Javascript toggle hide

本文关键字:隐藏 Javascript      更新时间:2023-09-26

我正在学习javascript,我正在尝试切换一个简单的隐藏和显示效果,但没有运气。目前,只有通过单击具有相同引用的另一个div才能取消效果。

这是我的javascript:

var $ = jQuery;
$(document).ready(function(){
    $('.section').hide(); 
});
function showMe(num){
    $('.section').hide(0);   
    $('#div_one'+num).fadeIn(1000); 
}

这是我的 CSS:

.height-auto
{
    height:auto;
}
.section
{
    width:552px;
    min-height:300px;
}

这是我的 HTML:

    <div class="section home-things visible" id="div_one1">
        <div class="section-contents"></div>
    </div>
</div>

理想情况下,我希望"javascript:showMe(1)"切换"div_one1"等等。

请帮忙

你编写的代码纯粹是一个 show 函数。你每次调用showMe都隐藏它,然后显示它。

如下所示的内容可以使其成为实际的切换:

function showMe(num)
{
    if ($('#div_one'+num).is(":visible"))
    { // the div is visible, so we just want to hide it
        $('#div_one'+num).hide();
    }
    else
    { // the div is not visible, so hide the rest and show it
        $('.section').hide(0);
        $('#div_one'+num).fadeIn(1000);
    }
    // I don't know what these next two lines are for,
    // as your code sample doesn't include them, so leaving as-is :)
    $('.height-auto').removeClass('height-auto');
    $('#strict').addClass('height-auto');
}

但是,jQuery有一些方便的内置函数,可以使其更短一些:

function showMe(num)
{
    $('#div_one'+num).siblings('.section').hide();
    $('#div_one'+num).fadeToggle();
    // I don't know what these next two lines are for,
    // as your code sample doesn't include them, so leaving as-is :)
    $('.height-auto').removeClass('height-auto');
    $('#strict').addClass('height-auto');
}

js小提琴

我迟到了,但为你构建了它,所以只是作为答案发布

$(document).ready(function(){
    $('.section').hide(); 
    $('#div_one1').show();
});
function showMe(num){
    $('.section').hide();
    $('#div_one'+num).fadeIn(300); 
}

演示。