program story

jQuery bind click * ANYTHING * but * ELEMENT *

inputbox 2020. 11. 10. 08:05
반응형

jQuery bind click * ANYTHING * but * ELEMENT *


주위에 떠 다니는 요소가 몇 개 있다고 가정하고, ANYTHING (divs, body, whatever ...)을 클릭 할 때 일부 작업을 수행하려고하지만 지정된 요소 (예 : div # special)를 클릭합니다.

내가 생각할 수있는 다음 방법 외에 이것을 달성하는 더 좋은 방법이 있는지 궁금합니다 ...

$(document).bind('click', function(e) {
    get mouse position x, y
    get the element (div#special in this case) position x, y
    get the element width and height
    determine if the mouse is inside the element
    if(inside)
        do nothing
    else
        do something
});

" 요소를 클릭 할 때를 제외하고 수행 "상황 을 처리하기 위해 일반적인 접근 방식은 "이 작업을 수행"하는 경우를 처리하는 이벤트 처리기를 추가 한 다음 "이 항목을 제외하고"요소에 다른 이벤트 처리기를 추가하는 것입니다. 클릭 이벤트 버블 링을 방지합니다 .documentdocument

$('#special').on('click', function(e) {
    e.stopPropagation();
});

$(document).on('click', function (e) {
 // Do whatever you want; the event that'd fire if the "special" element has been clicked on has been cancelled.
});

참조 문서를 . jQuery 1.7 이전 버전을 사용하는 경우 (이 질문을했을 때와 마찬가지로) 사용할 수 없습니다 . 대신 간단하게 with 의 두 가지 용도를 대체하십시오 . 이 경우 서명은 동일합니다.event.stopPropagation()on()on()bind()

여기에서 데모; http://jsfiddle.net/HBbVC/


당신은 또한 할 수 있습니다

$(document).bind('click', function(e) {
  if(!$(e.target).is('#special')) {
    // do something
  }
});

또는 div # special에 자식 요소가 있으면 할 수 있습니다.

$(document).bind('click', function(e) {
  if($(e.target).closest('#special').length === 0) {
    // do something
  }
});

나는 과거에 이렇게 해왔다.

jQuery("body").bind("click", function(e)
{
    var obj = (e.target ? e.target : e.srcElement);
    if (obj.tagName != 'div' && obj.id != 'special')
    {
        // Perform your click action. 
        return false;
    }
});

div # special을 클릭하지 않은 경우에만 실행됩니다. 솔직히 더 나은 방법이 있을지 모르지만 이것은 나를 위해 일했습니다.


다른 바인딩을 수행해야합니다.이 모든 클릭을 하나의 기능으로 처리 할 필요가 없습니다.

$('body').bind('click', function(e){
  bodyClickEvent();
});
$('div.floating').bind('click',function(e){
  elementClickEvent(this);
  e.stopPropagation(); //prevents bodyClickEvent
});
  $('div#special').bind('click', function(){
  e.stopPropagation(); //prevents bodyClickEvent
});

I wrote this today for an issue i was having as i don't like having click events bound to the document the whole time, so for my scenario this works, using callbacks from functions.

$('#button').click(function(){
        //when the notification icon is clicked open the menu
        $('#menu').slideToggle('slow', function(){
            //then bind the close event to html so it closes when you mouse off it.
            $('html').bind('click', function(e){
                $('#menu').slideToggle('slow', function(){
                    //once html has been clicked and the menu has closed, unbind the html click so nothing else has to lag up
                    $('html').unbind('click');
                });
            });
            $('#menu').bind('click', function(e){
                //as when we click inside the menu it bubbles up and closes the menu when it hits html we have to stop the propagation while its open
                e.stopPropagation();
                //once propagation has been successful! and not letting the menu open/close we can unbind this as we dont need it!
                $('#menu').unbind('click');
            });
        });
    });

참고URL : https://stackoverflow.com/questions/6635659/jquery-bind-click-anything-but-element

반응형