js點擊出現懸浮窗效果不使用JQuery外掛程式

來源:互聯網
上載者:User

JQuery有很多這樣的外掛程式,但是我們公司不用jquery,沒有外掛程式,所以我就試著自己寫,我也不知道別人是怎麼寫的,純粹是按著自己的想法來的。

直接上代碼:
複製代碼 代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<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';
}
}

</script>
<style type="text/css">
*{
margin: 0px;
padding: 0px;
}
div{
width: 60px;
height: 100px;
background: #33ccff;
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>

複製到本地就可以測試了。

這裡要說一下cancelBubble這兩個東西。因為我做的效果是點擊按鈕就顯示div,點擊頁面的任意位置div就消失,但javascript的冒泡機制是button獲得一個onclick事件後,往上冒泡,dom在獲得一個onclick事件,這樣的話就和讓div消失的onclick事件衝突了,所以需要event.cancelBubble = true;這行代碼來停止冒泡。大體就是這樣,代碼很簡單。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.