Подтвердить что ты не робот

Как определить, нажата ли мышь, кроме элемента $(this)

Я хочу применить некоторый стиль, если мышь нажата внутри элемента (здесь .block). Если элемент щелкнут, получите этот элемент $(this) и создайте его. Теперь после этого, когда пользователь нажимает кнопку, отличную от элемента $(this), я хотел бы изменить его на стиль по умолчанию. Как определить, нажата ли мышь, кроме элемента $(this).

js script:

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

4b9b3361

Ответ 1

Вы можете связать событие click на 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')
    }
})
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>

Ответ 2

Лучший способ сделать это - использовать tabindex andd 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>

Ответ 3

Вы можете попробовать что-то вроде этого: -

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

Ответ 4

Добавьте класс CSS, который представляет стили и выбранное состояние выбранного в данный момент блока:

.block.selected {
  background: red;
}

Внутри обработчика щелчка удалите этот класс из выбранного блока. (Если ни один из блоков не выбран, removeClass() ничего не сделает.) Затем добавьте класс в блок с новым щелчком:

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

Fiddle 1


Обновление

Как узнать, нажата ли она внутри блока или другого .block

Используйте hasClass(), чтобы определить, дважды ли вы нажали один и тот же блок:

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

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

Fiddle 2

Ответ 5

сделать это в 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>

Ответ 6

См. комментарии в приведенном ниже примере рабочего кода.

<!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 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 new?");
                });
            });
        </script>
    </body>
</html>

Ответ 7

На основании ответа 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/