单击更改 div 样式 + 单击外部 div 删除样式更改



我想通过点击更改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>

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

以下操作应该可以:

$(document).on('click', function(e) {
    if($(e.target).hasClass('account')) {
        // do style change
    }
    else {
        // undo style change  
    }
});
它将事件处理程序

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

试试这个。

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

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

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

试试这个:

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

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

最新更新