Home  >  Article  >  Web Front-end  >  js click to display floating window effect without using JQuery plug-in_javascript skills

js click to display floating window effect without using JQuery plug-in_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:03:011184browse

There are many such plug-ins for JQuery, but our company does not use jQuery and has no plug-ins, so I tried to write it myself. I don’t know how others wrote it, so I just followed my own ideas.

Add the code directly:

Copy the code The code is as follows:

< !DOCTYPE html>



Demo
< 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';
}
}










Copy it locally and you can test it.

Here are two things to talk about: cancelBubble. Because the effect I made is that clicking the button will display the div, and clicking anywhere on the page will make the div disappear. However, the bubbling mechanism of JavaScript is that after the button gets an onclick event, it bubbles up, and the dom gets an onclick event. In this case, It conflicts with the onclick event that makes the div disappear, so the event.cancelBubble = true; line of code is needed to stop bubbling. That's it, the code is very simple.
Statement:
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