开发者

checkExternalClick is doing the opposite of what I want it to do?

I previously asked a question as to how to make a b开发者_Python百科ox close when the user clicks anywhere outside of it, after trying the background overlay as given in this questions's answer by Jason Striegel. But it was not working and not much attention was received. I'm now attempting to approach the problem from the other answer, given by Aaron Ray. He suggested the checkExternalClick. I've set it up, but now the box closes whenever I click anywhere inside the box, not anywhere outside!

JS:

$(document).ready(function(){
    initHUDWindow();
});

function initHUDWindow()
{
    $(document).mousedown(checkExternalClick);  
}

function checkExternalClick(event)
{
   var target = $(event.target);
   if(target[0].id != "box")
   {        
      hideBox();
   }
}

function hideBox()
{
   $(".BoxContainer").hide();
}

CSS:

.Box
{
position:absolute;
top:15%;
left:15%;
width:500px;
height:600px;
background-repeat:no-repeat;
z-index:2;
}


.BoxContainer
{
background-image:url('images/box.png');
z-index:2;
}

HTML:

<div id = "box">
   <div class = "Box BoxContainer"></div> 
</div>

As I said, this will close the box when the user clicks inside the box. But wait! I thought it was supposed to close the box if they clicked outside?


Try this

$(document).ready(function(){
    initHUDWindow();

    $("#box").click(function(e){
        e.stopPropagation();
    });

});

function initHUDWindow()
{
    $(document).click(checkExternalClick);  
}

function checkExternalClick(event)
{
   hideBox();
}

function hideBox()
{
   $(".BoxContainer").hide();
}


I'm not sure this is the best approach overall, but the issue here is that elements within the element do not have that ID. I think this will fix it though (untested):

function checkExternalClick(event)
{
   var target = $(event.target);
   if(target[0].id != "box" && target.closest("#box").length === 0)
   {        
      hideBox();
   }
}

This should check that you haven't clicked on the element or any element within it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜