Home > Web Front-end > JS Tutorial > Clicking outside the div area to hide the div area_javascript skills implemented by js

Clicking outside the div area to hide the div area_javascript skills implemented by js

WBOY
Release: 2016-05-16 16:42:53
Original
1583 people have browsed it

First, let’s take a look at the JS event model. The JS event model is upward bubbling. For example, after an onclick event is triggered on a certain DOM element, the event will propagate upward following the node until a click event is bound to a certain parent node. , if not it will go up to the root of the document.

Prevent bubbling: 1. stopPropagation() for non-IE browsers. 2. The cancelBubble attribute is true, for IE browser,

Jquery already has a browser-compatible method, event.stopImmediatePropagation();

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="js/jquery-1.4.4.min.js" ></script>
<title></title>
</head>
<style type="text/css">
body
{
background-color:#999999;
}

#myDiv
{
background-color:#FFFFFF;
width:250px;
height:250px;
display:none;
      }
  </style>
<body>
<input id="btn" type="button" value="显示DIV" />

<div id="myDiv">
This is a div;
</div>

</body>

<script type="text/javascript">
    var myDiv = $("#myDiv");
$(function ()
{
$("#btn").click(function (event) 
{
showDiv();//调用显示DIV方法
$(document).one("click", function () 
{//对document绑定一个影藏Div方法
$(myDiv).hide();
});

event.stopPropagation();//阻止事件向上冒泡
});
$(myDiv).click(function (event) 
{

event.stopPropagation();//阻止事件向上冒泡
});
});
    function showDiv() 
{
$(myDiv).fadeIn();
}
</script>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template