javascript每日一练(八)——事件三:默认行为

时间:2023-03-08 17:57:12
javascript每日一练(八)——事件三:默认行为

一、阻止默认行为

  return false;

自定义右键菜单

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
*{ margin:0; padding:0;}
#ul1{ list-style:none; display:none; width:100px; padding:5px; background:#ddd; border:1px solid ddd; color:#333; line-height:24px; position:absolute;}
</style>
<script>
document.oncontextmenu = function(ev)
{
    var oEvent = ev || event;
    var oUl = document.getElementById('ul1');
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;

    oUl.style.left = oEvent.clientX + 'px';
    oUl.style.top = oEvent.clientY + scrollTop + 'px';
    oUl.style.display = 'block';
    return false;
};

document.onclick = function()
{
    var oUl = document.getElementById('ul1');
    oUl.style.display = 'none';
};

</script>
</head>

<body style="height:2000px;">
<ul id="ul1">
    <li>复制</li>
    <li>粘贴</li>
    <li>剪切</li>
    <li>撤销</li>
</ul>
</body>
</html>

拖拽

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
#div1{ width:100px; height:100px; background:red; position:absolute;}
</style>
<script>
window.onload = function()
{
    var oDiv = document.getElementById('div1');
    var disX = 0;
    var disY = 0;

    oDiv.onmousedown = function(ev)
    {
        var oEvent = ev || event;
        disX = oEvent.clientX - oDiv.offsetLeft;
        disY = oEvent.clientY - oDiv.offsetTop;

        document.onmousemove = function(ev)
        {
            var oEvent = ev || event;
            var iX = oEvent.clientX - disX;
            var iY = oEvent.clientY - disY;

            if(iX < 0)
            {
                iX = 0;
            }
            else if( iX > document.documentElement.clientWidth - oDiv.offsetWidth)
            {
                iX = document.documentElement.clientWidth - oDiv.offsetWidth;
            }
            if(iY < 0)
            {
                iY = 0;
            }else if( iY > document.documentElement.clientHeight - oDiv.offsetHeight)
            {
                iY = document.documentElement.clientHeight - oDiv.offsetHeight;
            }

            oDiv.style.left = iX + 'px';
            oDiv.style.top = iY + 'px';
        };

        document.onmouseup = function()
        {
            document.onmousemove = null;
            document.onmouseup = null;
        };

        return false;

    };
};
</script>
</head>

<body>
<div id="div1"></div>
</body>
</html>