Remove / add class when based on toggle

时间:2016-11-12 05:44:54

标签: javascript jquery html css

I have a column that slides to the left on a click function. I then add the class of w to the container to change its width once the column slides out. What I am trying to do is add the class of e when it slides back in and then remove the class of w by wrapping it in the toggle functions, but the container still contains the class of w and won't add the class of e. Thoughts?

FIDDLE: http://jsfiddle.net/QDUQk/1926/

.container {
  border: 1px solid #000;
  width: 200px;
}

.container.e {
  width: 80%;
}

.container.w {
  width: 100%;
}

<div class="togl">Menu</div>
<div class="col">
  SLIDE ME SLIDE ME PLX PLX
</div>
<div class="container">
</div>

$('.togl').click(function() {
  if ($('.container').is(':visible')) {
    $('.col').toggle('slide', {
      direction: 'left'
    }, 1000, function() {
      $('.container').addClass('w');
      $('.container').removeClass('e');
    });
  } else {
    $('.col').toggle('slide', {
      direction: 'left'
    }, 1000, function() {
      $(".container").removeClass('w');
      $(".container").addClass('e')
    });
  }
});

2 个答案:

答案 0 :(得分:1)

The visibility of .container does not change from true. Check for "w" className at .is()

$('.togl').click(function() {
  if (!$('.container').is('.w')) {
    $('.col').toggle('slide', {
      direction: 'left'
    }, 1000, function() {
      $('.container').addClass('w');
      $('.container').removeClass('e');
    });
  } else {
    $('.col').toggle('slide', {
      direction: 'left'
    }, 1000, function() {
      $(".container").removeClass('w');
      $(".container").addClass('e')
    });
  }
});

jsfiddle http://jsfiddle.net/QDUQk/1927/

答案 1 :(得分:0)

点击时您的容器可见性不会改变。试试以下,

$('.togl').click(function() {
   if ($('.container').hasClass('e')) {
      $('.col').toggle('slide', {
                      direction: 'left'
      }, 1000, function() {
    $('.container').addClass('w');
    $('.container').removeClass('e');
  });
} else {
$('.col').toggle('slide', {
  direction: 'left'
}, 1000, function() {
  $(".container").removeClass('w');
  $(".container").addClass('e')
});
}});