前端基础知识

右键菜单

2017-08-25  本文已影响0人  LorenaLu
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>右键菜单</title>
        <style type="text/css">
            *{margin:0;padding:0}
            ul{
                position: absolute;
                width:100px;
                list-style: none;
                display: none;
            }
            ul li{
                padding: 10px;
                background: #AFB9DE;
                border: 1px solid #ccc;
                border-radius: 3px;
                color: white;
                cursor : pointer;
            }
            ul li:hover{
                background: #E86F6F;
            }
            li ul{
            }
        </style>
    </head>
    <body>
        <ul id="menu">
            <li>Java</li>
            <li>
                JavaScript
                <ul>
                    <li>基础</li>
                    <li>DOM</li>
                    <li>
                        BOM
                        <ul>
                            <li>window</li>
                            <li>location</li>
                            <li>navgatior</li>
                        </ul>
                    </li>
                    <li>jQuery</li>
                </ul>
            </li>
            <li>C</li>
        </ul>
    </body>
    <script type="text/javascript">
        var menu = document.querySelector("#menu");
        var lis = document.querySelectorAll("li");
        for(var i=0;i<lis.length;i++){
            lis[i].onmouseenter  = function(){
                var children = this.querySelector("ul");
                if(children){
                    children.style.left = this.offsetWidth + this.offsetLeft + "px";
                    children.style.top = this.offsetTop + "px";
                    children.style.display = "block";
                    console.log( this.offsetWidth+"--"+this.offsetLeft+"--"+this.offsetTop)
                }
            }
            lis[i].onmouseleave = function(){
                var children = this.querySelector("ul");
                if(children){
                    children.style.display = "none";
                }
            }
        }
        menu.onmouseleave = function(){
            this.style.display = "none";
        }
        document.oncontextmenu = function(ev){
            var x = ev.clientX , y = ev.clientY;
            menu.style.display = "block";
            menu.style.left = x + "px";
            menu.style.top = y + "px";
            return false;//取消对象的默认动作就可以return false。
        }
    </script>
</html>

上一篇下一篇

猜你喜欢

热点阅读