自定义网站右键菜单

初中的时候,我接触过一个通过侦听oncontextmenu并计算元素位置的方法。在新的html5 contextmenu规范出来前,这个方案还是比较通用的.而且这个菜单可以是任意HTML元素,这就提供了很大的可定制空间,比如可以在菜单里放一个播放器(右键即可看到)。下面给出主要代码:

<div id="context-menu" style="visibility:hidden">
	<div id="aplayer">
	</div>
	<a class="context-menu-item" href="javascript:void(0)">
		Close
	</a>
	<a class="context-menu-item" href="#">
		Top
	</a>
	<a class="context-menu-item">
		Copy
	</a>
</div>
<div id="aplayer-lrc">
</div>
#context-menu {
    position: absolute;
    background: white;
    border: 2px solid;
    list-style: none;
    display: block;
    z-index: 2147483647;
}

.context-menu-item {
    display: flex;
    cursor: pointer;
    padding: 8px 15px;
    align-items: center;
    border-top: 2px dashed;
	border-bottom: 2px solid transparent;
	border-left: none;
	border-right: none;
}

.context-menu-item:hover {
	border-top: 2px dashed;
	border-bottom: 2px solid transparent;
	border-left: none;
	border-right: none;
}

a.context-menu-item {
	color: #1a1a1a;
}

a.context-menu-item:hover {
	color: #007acc;
}

#aplayer {
    max-width: 300px;
	max-height: 170px;
}
(($) => {
    var menu = $('#context-menu'), body = $('body'), w, h, l, t, op = false, fr = true, cl = () => {
        op = false
        menu.hide()
    }

    $(document).contextmenu((e) => {
        e.preventDefault()
        if (op) {
            cl()
        } else {
            if (!w || !h) {
                w = menu.width(), h = menu.height()
            }
            if ((w + e.clientX) >= $(window).width()) {
                menu.css('left', (e.pageX - w) + "px")
            } else {
                menu.css('left', e.pageX + "px")
            }
            if ((h + e.clientY) >= $(window).height()) {
                menu.css('top', (e.pageY - h) + "px")
            } else {
                menu.css('top', e.pageY + "px")
            }
            if (fr) {
                menu.css('visibility', '')
                fr = false
            }
            menu.show()
            op = true;
            ({ left: l, top: t } = menu.offset())
        }
    }).click((e) => {
        if (op && (e.pageX < l || e.pageX > l + w || e.pageY < t || e.pageY > t + h)) cl()
    })

    $('.context-menu-item').click(() => cl())
})(jQuery);

由于Aplayer在计算播放列表的时候用到了scrollHeight属性,这里需要在第一次加载时使用visibility隐藏元素.

Leave a Reply

Your email address will not be published. Required fields are marked *