문제
표시되는 부동 div가 있는데 사용자가 div를 클릭하면 숨겨지길 원합니다.이는 요소 위로 마우스를 가져갈 때 .hover() 함수 콜백과 유사합니다.클릭에 대해서만 이 작업을 수행하고 싶습니다.
div를 숨기는 본문에 대한 클릭 이벤트를 설정하려고 시도했지만 예상치 못한 결과가 발생했습니다.
내가 어떻게 쉽게 할 수 있는지에 대한 아이디어가 있는 사람이 있나요?
해결책
또 다른 더 간단한 옵션은 플로팅 DIV와 페이지의 나머지 부분 사이에 투명한 div를 추가하는 것입니다.
투명한 DIV의 간단한 클릭 이벤트는 숨김을 처리할 수 있으며 클릭 이벤트에서 발생하는 문제를 피할 수 있습니다.
다른 팁
페이지의 다른 곳을 클릭하면 DIV를 지우려면 다음과 같은 작업을 수행 할 수 있습니다.
$('body').click(function(event) {
if (!$(event.target).closest('#myDiv').length) {
$('#myDiv').hide();
};
});
jQuery를 사용하는 경우 다음과 같은 선택기를 사용할 수 있습니다.
$("*:not(#myDiv)").live("click", function(){
$("#myDiv").hide();
});
확실히 당신은 흐림 이벤트?
이 작업을 수행하는 가장 좋은 방법은 다음과 같습니다.-
$(document).bind('click', function(e) { var $clicked = $(e.target); if (!$clicked.parents().hasClass("divtohide")) { $(".divtohide").hide(); } });
이것은 나를 위해 일했습니다.
var mouseOver = false;
$("#divToHide").mouseover(function(){mouseOver=true;});
$("#divToHide").mouseout(function(){mouseOver=false;});
$("body").click(function(){
if(mouseOver == false) {
$("#divToHide").hide();
}
});
예제 링크 요소를 클릭하여 디스플레이 메뉴를 표시하면 Blur 함수를 바인딩하여 DIV 메뉴를 숨기기 위해 요소를 연결합니다.
$('a#displaymenu').click(function(){
$("#divName").toggle();
}).blur(function() {$("#divName").hide()})
이것은 클릭 아웃 이벤트를 처리하는 기능이며 팝업의 선택기와 jQuery 요소를 공급합니다. 아마도 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);
};
따라서 팝업 요소와 같은 경우 <div class='popup'>test</div>
내 기능을 사용할 수 있습니다 clickOut("div.popup", $("div.popup"));
$('body').click(function (event) {
if ($("#divID").is(':visible')) {
$('#divID').slideUp();
}
});
이것은 DIV가 보이는지 확인하는 데 사용될 수 있습니다.
본격적인 이벤트 중심 접근 방식이 있습니다
- 사용자 정의 이벤트는 다른 클릭 기반 이벤트의 발가락을 밟지 않도록 레이어의 "소환"및 "해고"를 처리합니다.
- Document.body는 해고 이벤트에 대해서만 해당 계층이 실제로 보이는 경우에만 듣습니다.
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>
그것은 내가 아는 많은 코드이지만 여기에 다른 접근법을 보여주기 위해 여기에 있습니다.
당신은 이것을 시도 할 수 있습니다.http://benalman.com/projects/jquery-clickoutside-plugin/
문서에서 이벤트 핸들러를 사용하는 것이 좋습니다.
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; }
포럼에서 솔루션을 찾았지만 Orginal Author에게 신용을 다시 찾을 수는 없습니다. 다음은 버전입니다 (내 코드에 사는 수정).
$(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');
//...
}
또한 ESC KeyUp 바인딩과 위의 그림이 아닌 'Close'HTML 앵커가 있습니다.
스스로 클릭하여 표시 할 요소를 숨기고 싶지 않은 경우 :
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;
});
모니터링해야합니다 mouseDown
전체 페이지의 이벤트 이벤트이지만 사용자가 플로팅 DIV 내부를 클릭 할 때 주목해야합니다.
사용자가 호버링 할 때 떠 다니는 DIV에 호버 이벤트를 추가하는 것이 좋습니다. mouseDown
무시되지만 맴돌고 있지 않을 때 mouseDown
닫을 것입니다