简体   繁体   English

jQuery-单击时切换div类

[英]jQuery - Toggle div class on click

No, this is not a straight forward toggle question. 不,这不是一个直接的切换问题。 I am aware of the toggle() functions and how to simply hide/show a div. 我知道toggle()函数以及如何简单地隐藏/显示div。 Imagine a box with a label inside: 想象一个带有标签的盒子:

<div class="section hidden">
    <div class="section-legend">My Section</div>
</div>

When you click anywhere on the entire div, it should remove class hidden . 当您在整个div上的任意位置单击时,它应删除class hidden The box then looks expanded. 然后,该框将展开。 Now that the box is not of class hidden it should not be clickable. 现在,该框不是hidden的类,因此不应单击它。

Instead, when you click the div.section-legend it should add class hidden to the main div again. 相反,当您单击div.section-legend它应该再次向主div添加hidden的类。 Obviously the click event for the legend needs to stopPropagation(). 显然,图例的click事件需要stopPropagation()。 Now the legend should not be clickable anymore and once again you must click the entire div to open it. 现在,图例不再可单击,您必须再次单击整个div才能将其打开。

I can't get anything to work properly, and I know this is stupid code: 我什么都无法正常工作,而且我知道这是愚蠢的代码:

$(document).ready(function() {

    $('.section.hidden').click(function() {
        $(this).removeClass('hidden');
        $(this).find('.section-legend').click(function(e) {
            $(this).parent().addClass('hidden');
            e.stopPropagation();
        });
    });

    $('.section-legend').click(function(e) {
        $(this).parent().addClass('hidden');
        e.stopPropagation();
        $(this).parent().click(function() {
            $(this).removeClass('hidden');
        });
    });

}); });

$('.section-legend').live('click',function(){
    $(this).parent().toggleClass('hidden');
});

This is assuming the section-legend is just as large as it's container in 'hidden state'. 这是假设section-legend与处于“隐藏状态”的容器一样大。

EDIT: changed some code, solution is this: 编辑:更改了一些代码,解决方案是这样的:

$('.section').live('click',function(){
    $(this).removeClass('hidden');
});
$('.section-legend').live('click',function(){
    $(this).parent().toggleClass('hidden'); return false;
});

return false did the trick! return false的把戏! demo: http://jsfiddle.net/RUfN7/2/ 演示: http : //jsfiddle.net/RUfN7/2/

First add an onclick event on the div that needs clicking: 首先在需要点击的div上添加一个onclick事件:

<div id="myDiv" class="section hidden">
    <div class="section-legend" onclick="function1();">My Section</div>
</div>

And add this javascript to the html 并将此javascript添加到html

<script language="JavaScript">
    function function1(){
        document.getElementById("myDiv").removeAttribute("class");

    }
</script>
$('.section').click(function() {
    $(this).removeClass('hidden');
});

$('.section-legend').click(function(e) {
    var $parent = $(this).parent();
    if(!$parent.hasClass('hidden')) {
        $parent.addClass('hidden');
        return false;
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM