简体   繁体   English

jQuery单击元素事件

[英]jQuery click off element event

I have a floating div that gets displayed, and I want it to be hidden when the user clicks off the div. 我有一个浮动div显示,我希望它在用户点击div时隐藏。 This would be similar to the .hover() function callback when hovering off an element. 当悬停在元素上时,这类似于.hover()函数回调。 Only I want to do this for click. 只有我想点击才能这样做。

I tried just setting a click event for the body, which would hide the div, but that gave unexpected results. 我尝试只为身体设置一个点击事件,这会隐藏div,但这会产生意想不到的结果。

Anyone have ideas on how I could easily do this? 任何人都有关于我如何轻松做到这一点的想法?

If you want to clear the div when you click somewhere else in the page, you can do something like: 如果要在单击页面中的其他位置时清除div,可以执行以下操作:

$('body').click(function(event) {
    if (!$(event.target).closest('#myDiv').length) {
        $('#myDiv').hide();
    };
});

Another, possibly simpler, option would be to add a transparent div between the floating DIV and the rest of the page. 另一个可能更简单的选择是在浮动DIV和页面其余部分之间添加透明div。

A simple click event on the transparent DIV could handle the hiding, and it would avoid the issues you are encountering with the click event. 透明DIV上的简单点击事件可以处理隐藏,它可以避免您遇到click事件时遇到的问题。

If you're using Jquery, you could use a selector like: 如果你正在使用Jquery,你可以使用如下的选择器:

$("*:not(#myDiv)").live("click", function(){
    $("#myDiv").hide();
});

你肯定在寻找模糊事件吗?

The Best way to do this is:- 最好的方法是: -

$(document).bind('click', function(e) {  

 var $clicked = $(e.target);

    if (!$clicked.parents().hasClass("divtohide")) {
        $(".divtohide").hide();
    }

});

This worked for me, 这对我有用,

var mouseOver = false;
$("#divToHide").mouseover(function(){mouseOver=true;});
$("#divToHide").mouseout(function(){mouseOver=false;});
$("body").click(function(){
      if(mouseOver == false) {
           $("#divToHide").hide();
      }
});
     $('body').click(function (event) {        
if ($("#divID").is(':visible')) {
            $('#divID').slideUp();
        }
});

This can be used to check if the div is visible, if it is visible, it will then slide the object up. 这可以用来检查div是否可见,如果它是可见的,它将向上滑动对象。

This is a function to handle the click out event, I feed it the selector of the popup, and the jquery element. 这是一个处理clickout事件的函数,我将它提供给弹出窗口的选择器和jquery元素。 Probably better served as a jquery plugin, but this is simple enough. 可能更适合作为jquery插件,但这很简单。

clickOut = function(selector, element) {
 var hide = function(event) {
  // Hide search options if clicked out
  if (!$(event.originalEvent.target).parents(selector).size())
   $(element).hide();
  else
   $(document).one("click",hide);
 };

 $(document).one("click", hide);
};

So if you have a popup element like <div class='popup'>test</div> you can use my function like clickOut("div.popup", $("div.popup")); 因此,如果您有一个像<div class='popup'>test</div>这样的弹出元素,您可以使用我的函数,如clickOut("div.popup", $("div.popup"));

example you click a link element to display div menu , you simply bind blur function to link element to hide div menu 例如,您单击链接元素以显示div菜单,您只需将模糊功能绑定到链接元素以隐藏div菜单

$('a#displaymenu').click(function(){
   $("#divName").toggle();
}).blur(function() {$("#divName").hide()})

Here's a full-fledged event-driven approach 这是一个成熟的事件驱动方法

  • Custom events handle the "summoning" and "dismissing" of the layer as to not step on the toes of other click-based events 自定义事件处理图层的“召唤”和“解雇”,而不是踩到其他基于点击的事件的脚趾
  • document.body listens to for a dismiss event only when the layer in question is actually visible 仅当有问题的层实际可见时,document.body才会侦听dismiss事件

Zee code: Zee代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type="text/javascript">

$(function()
{
  var $layer = $('#layer');
  var $body  = $('html');

  $layer
    .bind( 'summon', function( e )
    {
      $layer.show();
      $body.bind( 'click', dismissLayer );
    } )
    .bind( 'dismiss', function( e )
    {
      $layer.hide();
      $body.unbind( 'click', dismissLayer );
    } )
    .click( function( e )
    {
      e.stopPropagation();
    })
    .trigger( 'dismiss' )
  ;

  function dismissLayer( e )
  {
    $layer.trigger( 'dismiss' );
  }

  // This is optional - this just triggers the div to 'visible'
  $('#control').click( function( e )
  {
    var $layer = $('#layer:hidden');
    if ( $layer.length )
    {
      $layer.trigger( 'summon' );
      e.stopPropagation();
    }
  } );
});

</script>

<style type="text/css">
#layer {
  position: absolute;
  left: 100px;
  top: 20px;
  background-color: red;
  padding: 10px;
  color: white;
}
#control {
  cursor: pointer;
}
</style>

</head>
<body>

<div id="layer">test</div>
<span id="control">Show div</span>

</body>
</html>

It's a lot of code I know, but here just to show a different approach. 这是我所知道的很多代码,但这只是为了展示一种不同的方法。

Using an event handler on the document works well for me: 在文档上使用事件处理程序对我很有用:

function popUp( element )
{
    element.onmousedown = function (event) { event.stopPropagation(); };
    document.onmousedown = function () { popDown( element ); };

    document.body.appendChild( element );
}

function popDown( element )
{
    document.body.removeChild( element );

    document.onmousedown = null;
}

I've found the solution in a forum... but I can't find it back to credit the orginal author. 我在一个论坛中找到了解决方案......但我找不到它归功于原始作者。 Here is the version (modified that lives in my code). 这是版本(修改后的代码)。

 $(document).bind('mousedown.yourstuff', function(e) {
            var clicked=$(e.target); // get the element clicked                 
            if( clicked.is('#yourstuff')
                 || clicked.parents().is('#yourstuff')) {
                // click safe!
            } else {
                // outside click
                closeIt();
            }
        });

 function closeIt() {
        $(document).unbind('mousedown.emailSignin');
        //...
}

I also have ESC keyup bindings and a 'close' html anchor not pictured above. 我还有ESC keyup绑定和一个'close'html锚点,如上图所示。

If you do not want to hide the element that you will show by clicking itself: 如果您不想通过单击自己隐藏要显示的元素:

var div_active, the_div;

the_div = $("#the-div");
div_active = false;

$("#show-the-div-button").click(function() {
  if (div_active) {
    the_div.fadeOut(function(){
      div_active = false;
    });
  } else {
    the_div.fadeIn(function(){
      div_active = true;
    });
  }
});

$("body").click(function() {
  if div_active {
    the_div.fadeOut();
    div_active = false;
  }
});

the_div.click(function() {
  return false;
});

You're going to need to monitor the mouseDown event for the whole page, but you'll have to take note when the user is clicking inside your floating div. 您将需要监视整个页面的mouseDown事件,但是当用户在浮动div中单击时,您必须注意。

I would suggest adding a hover event to your floated div so when the user is hovering over it, mouseDown is disregarded, but when it is not being hovered over mouseDown would close it 我建议在你的浮动div中添加一个悬停事件,这样当用户将鼠标悬停在它上面时,会忽略mouseDown ,但是当它没有悬停在mouseDown会关闭它

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

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