js实现一个简单的自定义右键菜单

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/l344938248/article/details/80322519
var RightMenu = function(){
        this.rightMenu = null;
        this.rightMenuList = [];
        this.itemIndex = 0;
    }
    RightMenu.prototype = {
        init:function(){
            this._preventDefaultRightMenu(); //初始化时阻止默认事件
            this._createRightMenu();         //创建右键菜单
            this._rightClickEvent();         // 添加点击右键菜单的事件
        },
        _preventDefaultRightMenu:function(){
            document.addEventListener('contextmenu',function(event){ 
                event.preventDefault();
            },false)            
        },
        _createRightMenu:function(){
            this.rightMenu = document.createElement('ul');
            this.rightMenu.id = 'rightMenu';
            document.body.appendChild(this.rightMenu);
        },
        _rightClickEvent:function(){
            //给document绑定右键事件
            document.addEventListener('contextmenu',function(event){
                var menu = document.getElementById('rightMenu');
                menu.style.left = event.clientX + 'px';
                menu.style.top = event.clientY + 'px';
                menu.style.display = 'block';
            },false)            
        },
        _createRightMenuItem:function(item,callback){
            var li = document.createElement('li');
            li.id = 'rightMenuItem_' + this.itemIndex;
            li.innerHTML = item;
            this.rightMenu.appendChild(li);
            li.addEventListener('click',callback,false);
            this.itemIndex++;
        },
        addRightMenuItem:function(itemText,callback){ //供外部调用的方法传入两个参数(菜单文字,点击时的回调函数)
            this.rightMenuList.push(itemText);
            this._createRightMenuItem(itemText,callback);           
        }
    }
    //使用时初始化对象
    var rightMenu = new RightMenu();
    rightMenu.init();
    //添加右键菜单和回调函数
    rightMenu.addRightMenuItem('全选',function(event){
        alert('全选')
    });
    rightMenu.addRightMenuItem('单选',function(event){
        alert('单选')
    });
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页