jquery addClass / removeClass ain&work

时间:2017-07-09 10:13:31

标签: jquery

所以我尝试在div打开时添加和删除透明背景颜色,并在它关闭时删除。任何想法哦堆栈溢出的好主意?

HTML

<div class="col-md-12 col-xs-12">
    <div class="recipePicContainer">
        <div id="checkBoxes">
                <li class="recipe" id="recipe01"></li>
                       <ul class="ingredientsAndInstructions">
                           <li><input type="checkbox"> ingredient 1</li>
                           <li><input type="checkbox"> ingredient 2</li>
                           <li><input type="checkbox"> ingredient 3</li>
                           <li><input type="checkbox"> ingredient 4</li>
                            <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
                       </ul>
                </div>
            </div>
        </div>

CSS

.selected{
    background-color: #699e6d;
    opacity: 0.7;
}

JS

var main = function() {
    $(document).ready(function () {
        $('ul').hide();
        $('.recipe').click(function () {
            $('.ingredientsAndInstructions').toggle("slow");
            $('.recipePicContainer').click(function () {
                $(this).addClass("selected");
            }, function () {
                $(this).removeClass('selected');
            });
        });
    });
};
$(document).ready(main);

感谢名单!

1 个答案:

答案 0 :(得分:1)

使用toggleClass()

演示

$(document).ready(function() {
  $('button').click(function() {
    $('.recipes').toggleClass('selected');
  });
});
.recipes {
  display: none;
}

.selected {
  background-color: #699e6d;
  opacity: 0.7;
  display: block;
}
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>



<div class="col-md-12 col-xs-12">

  <button class='btn btn-primary'><h3>Recipes</h3></button>
  <ul class="recipes">
    <li><input type="checkbox"> ingredient 1</li>
    <li><input type="checkbox"> ingredient 2</li>
    <li><input type="checkbox"> ingredient 3</li>
    <li><input type="checkbox"> ingredient 4</li>
    <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
  </ul>

</div>


<script src="https://cdn.jsdelivr.net/g/jquery@2.2.4,bootstrap@3.3.7"></script>