2017-07-09 149 views
1

所以我試圖添加和刪除一個透明的背景顏色,一旦div打開,並在關閉時刪除。任何想法哦堆棧溢出偉大的思想?jquery addClass/removeClass不工作

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

使用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/[email protected],[email protected]"></script>

+0

優雅,效果很好! –

+0

很高興,先生。快樂的編碼。 – zer00ne