JS自定义右键菜单—复制到粘贴板(jQuery和原生JS实现)

自定义右键菜单——复制到粘贴板

需求:

  1. 鼠标在li标签上点击右键出现菜单,主要是复制等功能
  2. 屏蔽浏览器默认右键点击事件
  3. 右键菜单出现在鼠标点击的位置
  4. 点击屏幕其他位置菜单消失
  5. 点击之后有回调

实现:

1、使用jQuery - 右键菜单插件contextMenu

  1. 在项目中引入jquery.contextMenu.jsjquery.contextMenu.css
    同时 contextMenu 依赖 jQuery。
  2. 初始化插件

    $.contextMenu({
        selector: 'li',
        callback: function(key, options) {
            var Url2 = $(this).text().trim();
            var oInput = document.createElement('input');
            oInput.value = Url2;
            document.body.appendChild(oInput);
            oInput.select(); // 选择对象
            document.execCommand("Copy"); // 执行浏览器复制命令
            oInput.className = 'oInput';
            oInput.style.display = 'none';
            alert('成功复制到粘贴板');
        },
        items: {
            "copy": { name: "复制", icon: "copy" },
        }
    });
    

搞定!成功复制到粘贴板。

contextMenu插件:GitHub 主页
contextMenu插件:使用方法

2、使用原生js手撸一个

直接上代码:

html:
<div id="Rmenu">
    <ul>
        <li>复制</li>
        <li>删除</li>
    </ul>
</div>
CSS:
 * {
        margin: 0;
        padding: 0;
    }

    #Rmenu {
        width: 80px;
        background: #00AAAA;
        position: absolute;
        display: none;
        color: #fff;
        text-align: center;
        border-radius: 5px;
        cursor: pointer;
        -moz-box-shadow: 2px 2px 20px #333333;
        -webkit-box-shadow: 2px 2px 20px #333333;
        box-shadow: 2px 2px 20px #333333;
    }

    #Rmenu ul li:hover {
        font-size: 17px;
        background-color: #E1B700;
    }

    #Rmenu ul li {
        border-radius: 5px;
        list-style: none;
        margin: 5px;
        font-size: 16px;
    }
JS
window.onload = function() {
    var menu = document.getElementById("Rmenu");
    document.oncontextmenu = function(ev) {
        var ev = ev || event;
        menu.style.display = "block";
        menu.style.left = ev.clientX + "px";
        menu.style.top = ev.clientY + "px";
        //阻止默认右键事件
        return false;
    }
    document.onclick = function(e) {
        //click事件可以关闭右键菜单
        if (e.target.tagName.toLowerCase() === 'li') {
            console.log("您点击的是:" + e.target.outerText);
        }
        menu.style.display = "none"; 
    }
}

结果:


猜你喜欢

转载自blog.csdn.net/caomage/article/details/81032208