JQuery has many such plug-ins, but our company does not need jquery or plug-ins, so I try to write it myself, and I don't know how others write it, it is purely based on your own ideas.
Directly run the Code:
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Meta charset = "UTF-8">
<Title> Demo </title>
<Script type = "text/javascript">
Window. onload = function (){
Var btn = document. getElementsByTagName ('click') [0];
Var flt = document. getElementsByTagName ('div ') [0];
Btn. onclick = function (){
Event. cancelBubble = true;
Var x = btn. offsetLeft-15 + 'px ';
Var y = btn. offsetTop-100 + 'px ';
Flt. style. top = y;
Flt. style. left = x;
Flt. style. display = 'block ';
}
Document. onclick = function (){
Flt. style. display = 'none ';
}
}
</Script>
<Style type = "text/css">
*{
Margin: 0px;
Padding: 0px;
}
Div {
Width: 60px;
Height: 100px;
Background: #33 ccff;
Display: none;
Position: absolute;
}
Div ul {
Text-align: center;
}
Div li {
List-style-type: none;
}
Button {
Top: 300px;
Left: 400px;
Position: absolute;
}
</Style>
</Head>
<Body>
<Button id = "btn"> Click </button>
<Div>
<Ul id = "nav">
<Li class = "item1"> <a href = ""> Demo 1 </a> </li>
<Li class = "item2"> <a href = ""> Demo 2 </a> </li>
<Li class = "item3"> <a href = ""> Demo 3 </a> </li>
<Li class = "item4"> <a href = ""> Demo 4 </a> </li>
<Li class = "item5"> <a href = ""> Demo 5 </a> </li>
</Ul>
</Div>
</Body>
</Html>
Copy the file to the local device to test it.
Here are two things: cancelBubble. The result is that the div is displayed when you click the button and the div disappears when you click any position on the page. However, the javascript bubble mechanism is that after the button obtains an onclick event, it bubbles up, dom obtains an onclick event, which is in conflict with the onclick event that causes the div to disappear. Therefore, event is required. cancelBubble = true; this line of code stops bubbling. In general, the code is very simple.