vue实现右键菜单栏_vue.js_

2022年4月17日09:25:42

本文实例为大家分享了vue实现右键菜单栏的具体代码,供大家参考,具体内容如下

vue实现右键菜单栏和原生js大同小异,都是需要明白两个点

1.contextmenu事件是鼠标的右键点击事件
2.要阻止浏览器的默认右键事件

代码如下

// methods
rightShow() {
    let menu = this.$refs.msgRightMenu
    this.isPersoncontextMenus = true
    var evt = event || window.event;
        var clientWidth = document.documentElement.clientWidth || document.body.clientWidth ;
        var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
    
        var clientHeight = document.documentElement.clientHeight || document.body.clientHeight ;
        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop ;
    
        //给left和top分别赋值为鼠标的位置;
        menu.style.left = evt.pageX+"px";
        menu.style.top = evt.pageY+"px";
        //如果鼠标右边放不下菜单,就把left的值的改了
        if(evt.pageX+100>clientWidth+scrollLeft){//菜单应该在鼠标左边;
            var left1 = evt.pageX-100;
            menu.style.left = left1+"px";
        }
        //如果鼠标下边放不下菜单,就把top的值的改了
        if(evt.pageY+100>clientHeight+scrollTop){
            var top1 = (evt.pageY-100);
            menu.style.top = top1+"px";
        }
    
        menu.style.display = "block";
},
showNo(){
    let menu = this.$refs.msgRightMenu
    menu.style.display = "none";
}
//css样式直供参考,根据自己的需要写样式
#menu{
    list-style: none;
    margin: 0px;
    padding: 0px;
    position: absolute;
    display: none;
    width: 100px;
    height: 100px;
    background-color: gray;
}

#menu li{
    margin: 0px;
    padding: 0px;
}
//html
<div @click.self="showNo">//这个是最外层的盒子,加self修饰符可以不与其他事件冲突
        <input type="text" @contextmenu.prevent="rightShow">    //这里的prevent修饰符可以直接阻止浏览器的默认行为
            <ul id="menu" ref="msgRightMenu" v-show="isPersoncontextMenus">//isPersoncontextMenus别忘了在data里定义这个变量
                <li>鱼香肉丝</li>
                <li>醋溜土豆丝</li>
                <li>麻辣小龙虾</li>
                <li>回锅肉</li>
            </ul>
</div>

效果

  • 作者:-=|=-  
  • 原文链接:https://blog.csdn.net/l17606145618/article/details/106521380
    更新时间:2022年4月17日09:25:42 ,共 1683 字。