Js click to appear suspended window effect without using JQuery plug in

  • 2020-03-30 01:23:12
  • OfStack

JQuery has a lot of plug-ins like this, but we don't use JQuery in our company, we don't have plug-ins, so I try to write my own, I don't know how others write it, it's just my own idea.

Direct code:
<!DOCTYPE html> 
<meta charset="utf-8"> 
<script type="text/javascript"> 
window.onload = function(){ 
var btn = document.getElementsByTagName('button')[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'; 

<style type="text/css"> 
margin: 0px; 
padding: 0px; 
width: 60px; 
height: 100px; 
background: #33ccff; 
display: none; 
position: absolute; 

div ul{ 
text-align: center; 

div li{ 
list-style-type: none; 
top: 300px; 
left: 400px; 
position: absolute; 
<button id="btn">Click</button> 
<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> 

Copy it locally and you can test it.

I'm going to talk about these two cancelBubble things. Because what I did was I clicked on the button and div was displayed, and div disappeared if I clicked anywhere on the page, but the javascript bubbling mechanism is that after the button gets an onclick event, it bubbles up, and the dom gets an onclick event, which conflicts with the onclick event that made the div disappear, so I need event.cancelbubble = true; This line of code stops the bubble. That's it. The code is simple.

Related articles: