开发者

Is it possible to do a mousedown function inside an element, but not the elements childen?

For example I have this code:

<style>
    .wrapper { width:1200px; height:800px; }
    .column { width:900px; height:800px; margin:auto -0; }
</style>

<div class="wrapper">
     <div class="column"> </div>
</div>

I want a mousedown function to be called when you click outside of the "column" but not inside the column. Is this pos开发者_C百科sible?

My current non-working code is:

$(".wrapper:not(.column)").mousedown(function(){
     alert("test");
});

UPDATE: I am actually using classes, not IDs.


What you'll want to do is put a mousedown event handler on your #column div also, but in that event handler, you want to prevent the event from bubbling up to its container elements.

$("#column").mousedown(function (e) {
  var event = e || window.event;
  if (event.stopPropagation) {
    event.stopPropagation();
  } else {
    event.cancelBubble = true;
  } 
});

Here's a full example: http://jsfiddle.net/YrXSM/


I don't think you can stop the function from being called from the children, but you can detect what was clicked. I'm not sure if this is the best way to do it, but this should work:

$("#wrapper").mousedown(function(e){
  if($(e.target).attr('id') == 'wrapper')
  {
    //do stuff
  }
});


The following will work by stopping mousedown events on elements with class column from bubbling, and will work so long as column elements are strictly contained within wrapper elements.

$(".wrapper").mousedown(function(evt) {
    alert("Mouse down!");
});

$(".column").mousedown(function(evt) {
    evt.stopPropagation();
});


$(".wrapper").mousedown(function(e) {
    if (this !== e.target) { return; }
    alert("test"); 
});

So, basically, we are testing whether the .wrapper element was clicked directly. If not, we disregard the event by returning.


$("#wrapper").mousedown(function(){
     alert("test");
});


The way I would approach this is to assign another event to #container onMouseDown that does nothing, and then prevents the event from bubbling up.


The example given using e.target is the best option, however there is the possibility in the general case that your .mousedown() function is bound to a more complicated selector, if that is the case you can use the following code.

$(".wrapper").mousedown(function(e){
    if ($('.wrapper').filter(e.target).size() > 0) {
         alert("test");
    }
});

Demo at: http://jsfiddle.net/9RPcb/1/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜