Onclick更改div样式+ onclick外部div删除样式更改

时间:2012-04-27 14:26:13

标签: javascript jquery onclick

我想用onclick更改div上的样式...并在单击div之外的某处时删除样式。

我有以下代码设置...如果您点击页面上的任何其他位置,有人可以帮我删除div上的样式吗?

<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>

非常感谢您给我的任何帮助!!!

4 个答案:

答案 0 :(得分:6)

以下应该这样做:

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

它将事件处理程序绑定到整个文档,因此对于调用e.stopPropagation()的更具体元素的任何事件处理程序都会遇到问题。

答案 1 :(得分:2)

试试这个。

$(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");
   });
});

工作演示 - http://jsfiddle.net/yLhsC/

请注意,如果页面上有很多元素,您可以使用ondelegate来处理account元素上的点击事件。

像这样。

如果使用jQuery 1.7 +

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

使用delegate

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

答案 2 :(得分:0)

您可以通过在body元素上附加Click侦听器来实现此行为,例如:

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

});

答案 3 :(得分:0)

试试这个:

$(document).ready(function() {

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


$(document).click(function(){  
    $('.selected').removeClass('selected');
});
});
相关问题