在外面单击时隐藏弹出窗口

时间:2018-07-04 07:48:00

标签: javascript html5

这是一个JavaScript弹出窗口的示例:

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_popup

您将如何修改它,以便在单击弹出窗口之外的任何位置时弹出窗口消失?我在epub3文档中使用了html5和javascript。

1 个答案:

答案 0 :(得分:0)

$('#trigger').bind('click touch', function(){
	$('#tooltip').show();
});			

$(document).bind('click touch', function(event) {
  if (!$(event.target).parents().addBack().is('#trigger')) {
    $('#tooltip').hide();
  }
});

// Stop propagation to prevent hiding "#tooltip" when clicking on it
$('#tooltip').bind('click touch', function(event) {
  event.stopPropagation();
});
			* {
				margin: 0;
				padding: 0;
			}
			
			body,
			html {
				height: 100%;
			}
			
			body {
				font-size: 14px;
				line-height: 1.5;
				font-family: Helvetica, Arial, sans-serif;
				color: #000;
			}
			
			#container {
				position: relative;
				min-height: 100%;
				width: 100%;
				max-width: 960px;
				margin: 0 auto;
				zoom: 1;
			}
			
			#trigger {
				width: 200px;
				height: 200px;
				text-align: center;
				position: absolute;
				left: 0;
				right: 0;
				top: 0;
				bottom: 0;
				margin: auto;
				font-size: 22px;
				line-height: 200px;
				color: #fff;
				background: #ccc;
				cursor: pointer;
			}
			
			#trigger:hover {
				background: #0A9E01;
			}
			
			#tooltip {
				display: none;
				position: absolute;
				left: 10px;
				top: 10px;
				width: 250px;
				padding: 20px;
				font-size: 18px;
				color: #fff;
				background: #222222;
			}
			
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
	<head>
		<!--Meta Tags-->
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<meta http-equiv="imagetoolbar" content="no" />
		<meta name="author" content="mihai vaduva" />
		<meta name="email" content="" />
		<meta name="copyright" content="" />
		<meta name="distribution" content="global" />
		<meta name="rating" content="general" />
		<meta name="robots" content="noindex, nofollow" />
		<meta name="description" content=""/>
		<meta name="keywords" content=""/>
		
		<!-- include jQuery library -->
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
		
		<!--Title-->
		<title>Antimath - Hide if click outside</title>
	</head>
	<body>
		<!--container-->
		<div id="container">
			<noscript>
				<p class="warning">You have <a href="http://www.google.com/support/bin/answer.py?answer=23852">JavaScript disabled</a> or are viewing the site on a device that does no support JavaScript.Some features may not work properly.</p>
			</noscript>
			
			<div id="trigger">
				Click Me !
			</div>
			
			<div id="tooltip">
				Now click anywhere to hide it.
			</div>

		</div>
		<!--/container-->
	</body>
</html>