javascript每日一练(六)——事件一

时间:2020-12-06 23:19:35

一、event对象

  var oEvent = ev || event;//获取事件对象  oEvent.clientX  oEvent.clientY//获取鼠标坐标  oEvent.cancelBubble = true;//阻止冒泡

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
#div1{ width:100px; height:100px; background:red; display:none; position:absolute;}
</style>
<script>
window.onload = function(){
    var oBtn = document.getElementById('btn1');
    var oDiv = document.getElementById('div1');
    //event对象,用来获取事件的详细信息

    //获取鼠标位置
    document.onmousemove = function(ev){
        var oEvent = ev || event;
        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;

        oDiv.style.top = oEvent.clientY + scrollTop + 'px';
        oDiv.style.left = oEvent.clientX + 'px';
    };

    oBtn.onclick = function(ev){
        var oEvent = ev || event;
        oDiv.style.display = 'block';

        oEvent.cancelBubble = true;
    };

    document.onclick = function(){
        oDiv.style.display = 'none';
    };
};
</script>
</head>

<body style="height:2000px;">
<input id="btn1" type="button" value="显示" />
<div id="div1">
    <a href="http://baidu.com">百度</a>
</div>
</body>
</html>