简体   繁体   中英

Onclick change div style + onclick outside div remove style change

I would like to change the style on a div with an onclick... and remove the style when clicking somewhere outside of the div.

I have the following code setup... can someone help me to remove the style on the divs if you click anywhere else on the page?

<head>
  <style type="text/css">
     .account{
      width: 100px;
      height: 100px;
      border: 1px solid #000;
     }
    .selected{
     border: 2px solid #F00;
    }
  </style>
  <script type="text/javascript">
   $(document).ready(function(){
   $(".account").click(function(){
   $(".selected").removeClass("selected");
   $(this).addClass("selected");
  });   
  });
  </script>
</head>
<body>
 <h1>the test</h1>
 <div class="account">test 1</div>
 <div class="account">test 2</div>
</body>

Thank you very much for any help you can give me!!!

The following should do it:

$(document).on('click', function(e) {
    if($(e.target).hasClass('account')) {
        // do style change
    }
    else {
        // undo style change  
    }
});

It binds the event handler to the entire document, so you'd have problems with any event handlers on more specific elements that call e.stopPropagation() .

Try this.

$(document).ready(function(){
   $(".account").click(function(e){
       $(".selected").removeClass("selected");
       $(this).addClass("selected");
       e.stopPropagation();//This will stop the event bubbling 
   });   

   //This event handler will take care of removing the class if you click anywhere else
   $(document).click(function(){ 
       $(".selected").removeClass("selected");
   });
});

Working demo - http://jsfiddle.net/yLhsC/

Note that you can use on or delegate to handle click event on account elements if there are many on the page.

Something like this.

Using on if using jQuery 1.7+

$('parentElementContainingAllAccounts').on('click', '.account', function(e){
     $(".selected").removeClass("selected");
     $(this).addClass("selected");
     e.stopPropagation();//This will stop the event bubbling 
});

Using delegate

$('parentElementContainingAllAccounts').delegate('.account', 'click', function(e){
     $(".selected").removeClass("selected");
     $(this).addClass("selected");
     e.stopPropagation();//This will stop the event bubbling 
});

You can achieve this behavior with attaching click listener on body element eg:

$("body").click(function(){

});

Try this:

$(document).ready(function() {

$('.account').click(function(e) {
    e.stopPropagation();
    $(this).addClass("selected");
});


$(document).click(function(){  
    $('.selected').removeClass('selected');
});
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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