简体   繁体   English

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

[英]How to detect if mouse is clicked other than $(this) element

I want to apply some styling if mouse is clicked inside an element (here .block ). 如果在元素中单击鼠标(此处为.block ),我想应用一些样式。 If the element is clicked get that element by $(this) and style it. 如果单击该元素,则通过$(this)获取该元素并设置样式。 Now after that, when the user clicks other than the $(this) element, I would like to change it back to default styling. 此后,当用户点击$(this)元素以外的其他元素时,我想将其更改回默认样式。 How do I detect if mouse is clicked other than $(this) element. 如何检测鼠标是否被点击而不是$(this)元素。

js script so far : 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

});

jsfiddle 的jsfiddle

The better way to do this is using tabindex andd css :focus selector 更好的方法是使用tabindex和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 } 
 <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> 

You can try something like this:- 你可以尝试这样的事情: -

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

FIDDLE DEMO

You can bind the click event on the body and check if #a was clicked using e.target function 您可以绑定body上的click事件,并检查是否使用e.target函数单击了#a

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

Add a CSS class that represents the styles and selected state of the currently chosen block: 添加一个CSS类,表示当前所选块的样式和选定状态:

.block.selected {
  background: red;
}

Within the click handler, remove that class from the block that's selected. 在单击处理程序中,从所选的块中删除该类。 (If no blocks are selected, removeClass() won't do anything.) Then add the class to the newly-clicked block: (如果未选择任何块,则removeClass()将不执行任何操作。)然后将该类添加到新单击的块中:

$('.block').click(function() {
  $('.block.selected').removeClass('selected');
  $(this).addClass('selected');
});

Fiddle 1 小提琴1


Update 更新

How do I know whether it is clicked inside the block or other .block 我如何知道是否在块或其他.block中单击了它

Use hasClass() to determine if you've clicked the same block twice: 使用hasClass()来确定您是否两次单击同一个块:

 $('.block').click(function() { if($(this).hasClass('selected')) { // do something here } $('.block.selected').removeClass('selected'); $(this).addClass('selected'); }); 

Fiddle 2 小提琴2

doing it in JS would be something like 在JS中这样做会是这样的

 var globalRef; var inside = document.querySelectorAll('.inside'); document.querySelector('.block').addEventListener('click', function (e) { if (globalRef != undefined) { globalRef.style.background = 'none' } globalRef = e.target; e.target.style.background = 'red' }, false); 
 .block { width:200px; height:200px; background:#ccc; } .inside { display:inline-block; width:100px; height:100px; border:1px solid green; box-sizing:border-box; float:left } 
 <div class="block"> <div class='inside'></div> <div class='inside'></div> <div class='inside'></div> <div class='inside'></div> </div> 

See the comments in the working example code below. 请参阅下面的工作示例代码中的注释。

<!doctype html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
        <style>
            .block {
                background: gray;
                width: 100px;
                height: 100px;
                float: left;
                margin-left: 20px;
            }
        </style>
    </head>
    <body>
        <div class="block" id="block1"></div>
        <div class="block" id="block2"></div>
        <div class="block" id="block3"></div>
        <script type="text/javascript">
            $(document).ready(function() {
                /*
                Solution 1:
                This gathers all elements with the class 'block' and defines a click event on it.
                In the click event all elements with class 'block' are walked through. If an element
                has the same id as the current element's id, than do one thing else do another thing.
                In this example background color en content of the three divs are changed
                */
                $('.block').click(function(i) {
                    /*
                    Notice the usage of $(this) and this in the code below. $(this) Is the
                    jquery element while 'this' is the DOM element.
                    */
                    var block = $(this);
                    $(".block").each(function(){
                        if (this.id == block.attr("id")) {
                            this.innerHTML = ("My id is " + this.id);
                            this.style.background = "red";
                        } else {
                            this.innerHTML = "";
                            this.style.background = "gray";
                        }
                    })
                });
                /*
                Solution 2:
                For each element you want actions on, define a separate click event.
                */
                $('#block1').click(function(i) {
                  alert("You clicked me?");
                });
                $('#block2').click(function(i) {
                  alert("Why did you click me?");
                });
                $('#block3').click(function(i) {
                  alert("Hi there, what's new?");
                });
            });
        </script>
    </body>
</html>

Based on Akshay's answer: 根据Akshay的回答:

$('body').click(function (e) {
    var clicked = $(e.target);

    //See if the clicked element is (or is inside) a .block:
    var clickedBlock = clicked.closest('.block');
    if (clickedBlock.length) {
        clickedBlock.css('background', 'red');
    }

    //Remove the overridden background from other blocks:
    var allBlocks = $('.block');
    allBlocks.not(clickedBlock).css('background', '');
});

JSFiddle: http://jsfiddle.net/ftq8a6ex/5/ JSFiddle: http//jsfiddle.net/ftq8a6ex/5/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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