如何检测是否单击了$(this)元素以外的鼠标

Aam*_*amu 13 html javascript css jquery

如果在元素内单击鼠标(这里.block),我想应用一些样式.如果单击该元素,则获取该元素$(this)并对其进行样式化.此后,当用户点击$(this)元素以外的其他内容时,我想将其更改回默认样式.如何检测鼠标是否被单击而不是$(this)元素.

js脚本到目前为止:

$( document ).ready(function() {

    // when a block is clicked get that specific block
    $('.block').click(function() {
        var block = $(this);
        block.css('background','red');
    });

    //if clicked other than the block do stuff

});
Run Code Online (Sandbox Code Playgroud)

的jsfiddle

小智 14

更好的方法是使用tabindexandd css :focus选择器

.container{
  border:1px solid #333;
  width:200px;
  height:200px;
}
.block{
  background-color: #ccc;
  width:50px;
  float:left;
  height:50px;
  margin:20px;
}
.block:focus{
 background-color: red;
 outline:none
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <div class="block" id="block1" tabindex="1">
    </div>
  <div class="block" id="block2" tabindex="1">
    </div>
  <div class="block" id="block3" tabindex="1">
    </div>
  <div class="block" id="block4" tabindex="1">
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)


pal*_*aѕн 5

你可以尝试这样的事情: -

$(document).ready(function () {

    // when a block is clicked get that specific block
    $('.block').click(function () {
        var block = $(this);
        block.css('background', 'red');
    });

    //if clicked other than the block do stuff
    $('html:not(.block)').click(function () {
        //your logic here
    });
});
Run Code Online (Sandbox Code Playgroud)

FIDDLE DEMO


Aks*_*hay 4

您可以绑定点击事件并使用函数body检查是否#a被点击e.target

$('div').click(function () {
    $(this).css('background', 'red')
})
$('body').click(function (e) {
    if ($(e.target).is($("#a"))) {
        
    } else {
        $('#a').css('background','tomato')
    }
})
Run Code Online (Sandbox Code Playgroud)
div {
    width:100px;
    height:100px;
    background:tomato;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="a"></div>
Run Code Online (Sandbox Code Playgroud)