Javascript如何在用户单击其他位置时关闭上下文菜单

梅登

我有带有热点的HTML图像(HTML区域元素)。而且我有一些代码,当右键单击某个热点时可以显示上下文菜单,因为在某些情况下,该热点可以在逻辑上导航到多个目的地。

我有一些基于W3C Planets示例的不错的工作代码。我的菜单显示在靠近热点的地方,并且样式很好用。如果我单击某个项目,它将在其中导航。

菜单是动态的,并且实际上将由Angular代码和JSON进行复制。目前,菜单已通过模拟功能进行了硬编码。

如果单击某个项目,则菜单将消失(然后进行导航)。我知道隐藏菜单代码有效,因为我有一个用于测试的隐藏菜单按钮。

我的问题是,一旦菜单显示,我就无法弄清楚如何让用户关闭菜单$('body')。click(hideMenu)[第130行]无效,因为它不接受该函数作为指针(抱歉,如果条款错误),请稍后执行;即使我省略了括号,它也会立即执行它。

该代码可从JSFiddle的http://jsfiddle.net/simonmeaden/98mukrff/8/获得,尽管它不能在小提琴中使用。从Visual Studio启动的工作原理是什么。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <link href="contextMenus.css" rel="stylesheet" />
    <title></title>
</head>
<body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
    <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
    <script src="JavaScript1.js"></script>

    <table>
        <tr>
            <td>Some text to shift image along</td>
            <td>
                <img id="planets" src="http://www.w3schools.com/tags/planets.gif" usemap="#planetmap">
                <map name="planetmap" width="145" height="126" alt="Planets">
                    <area id="planetmap_AreaSun" shape="rect" coords="0,0,82,126" href="http://www.w3schools.com/tags/sun.htm" alt="Sun">
                    <area id="planetmap_AreaMercury" shape="circle" coords="90,58,3" href="http://www.w3schools.com/tags/mercur.htm" alt="Mercury">
                    <area id="planetmap_AreaVenus" shape="circle" coords="124,58,8" href="http://www.w3schools.com/tags/venus.htm" alt="Venus">
                </map>
            </td>
        </tr>
        <tr>
            <td>
                <ul class="context-menu" id="my_custom_menu">
                    <!--style="display:none;"-->
                    <li>Strawberry</li>
                    <li>Raspberry</li>
                </ul>
            </td>
        </tr>
    </table>
        <!--<button id="button_ShowMenu2" onclick="setMenu('my_custom_menu', this, dynamicMenu())" type="button">Show Menu</button> -->
        <button id="button_ShowMenu" type="button">Show Menu</button>
        <button id="button_HideMenu" onclick="hideMenu()" type="button">Hide Menu</button>

</body>

</html>

风格

.context-menu {
    /*position: absolute;*/
    display: block;
    background-color: #f2f2f2;
    border-radius: 4px;
    font-family: Arial, sans-serif;
    font-size: 14px;
    min-width: 150px;
    border: 1px solid #d4d4d4;
    z-index:1200;
    list-style-type: none;
    text-decoration: none;
}
.context-menu ul {
    list-style-type: none;
    margin: 4px 0px;
    padding: 0px;
    cursor: default;
}
.context-menu ul li {
    padding: 4px 16px;
}
.context-menu ul li:hover {
    background-color: #4677f8;
    color: #fefefe;
}


a {
    text-decoration: none;
}

.context-menu ul li a {
    text-decoration: none;
}

.context-menu ul li:hover a {
    text-decoration: none;
}

.context-menu ul li a:hover, a:hover span {
    background-color: #4677f8;
    color: #fefefe;
}

JavaScript

function hideMenu() {
    console.log("hideMenu entered");
    var sMenuId = $('body').data('data-activeMenu');
    if (sMenuId !== '') {
        var jqMenu = $('#' + sMenuId);

        if (jqMenu) {
            jqMenu.css('display', 'none');
        } else {
            alert("menu (ul) id '" + sMenuId + "' not found!");
        }
    } else {
        alert("menu id '" + sMenuId + "' is null!");
    }
}

$(document).ready(function () {

    wireUpContextMenu('#planetmap_AreaVenus');
    wireUpButton();
    var gMousepos = [0, 0];
    document.onmousemove = function (evt) {
        evt = evt || window.event;
        if (typeof evt.pageX != 'undefined') {
            // Firefox support
            gMousepos = [evt.pageX, evt.pageY];
        } else {
            // IE support
            var scrollpos = getDocScrollPos();
            gMousepos = [evt.clientX + scrollpos[0], evt.clientY + scrollpos[1]];
        };
    };


    //alert("run");

    function dynamicMenu() {
        var fruits = [{
            itemText: "Apple",
            href: "http:\/\/images.clipartpanda.com\/teacher-apple-clipart-apple-clipartclipart---simple-red-apple-3e7q8rci.png"
        }, {
            itemText: "Orange",
            href: "http:\/\/www.google.com"
        }, {
            itemText: "Banana",
            href: "http:\/\/www.bbc.co.uk"
        }, {
            itemText: "Grape",
            href: "http:\/\/www.hotmail.com"
        }];
        return fruits;
    }


    function wireUpContextMenu(elementId) {
        var elementForMenuLaunch = $(elementId);
        if (elementForMenuLaunch) {
            elementForMenuLaunch.bind('contextmenu', function (e) {
                e.preventDefault();
                var jqElement = $(this);
                //var mousepos=getMousePos();
                var position = jqElement.position();
                var lPixelLeft =  gMousepos[0];//position.left;
                var lPixelTop = gMousepos[1];//position.top;
                setMenuInner('my_custom_menu', lPixelLeft, lPixelTop, dynamicMenu());

                //alert('The eventhandler will make sure, that the contextmenu doesn\'t appear.');
            });

        } else {
            alert("elementForMenuLaunch '" + elementId + "'is not found!");
        }
    };

    //function getMousePos() {
    //}

    function getDocScrollPos() {
        var x = document.body.scrollLeft ||
                document.documentElement.scrollLeft ||
                window.pageXOffset || 0,
            y = document.body.scrollTop ||
                document.documentElement.scrollTop ||
                window.pageYOffset || 0;
        return [x, y];
    }

    function isIE(userAgent) {
        userAgent = userAgent || navigator.userAgent;
        return userAgent.indexOf("MSIE ") > -1 || userAgent.indexOf("Trident/") > -1;
    }

    function navigateTo(e) {
        console.log("hideMenu entered");
        hideMenu();
        var href = jQuery.data(this, 'data-href');
        console.log("called navigateTo " + href);
        window.location.href = href;  
    }




    function setMenuInner(sMenuId, lPixelLeft, lPixelTop, jsonItems) {
        //console.log("setMenu entered");
        if (sMenuId !== '') {
            var jqMenu = $('#' + sMenuId);

            if (jqMenu) {
                jqMenu.empty();


                //jQuery.data(document.body, 'data-activeMenu', sMenuId);

                //hideMenu();
                //$('body').click(hideMenu());

                var lItemCount = jsonItems.length;
                for (var i = 0; i < lItemCount; i++) {
                    var jqListItemNew = $("<li data-href='" + jsonItems[i].href + "'></li>").appendTo(jqMenu);
                    var jqAnchor = $("<a href='#'></a>" ).appendTo(jqListItemNew);
                    var jqSpan = $("<span data-href='" + jsonItems[i].href + "'>" + jsonItems[i].itemText + "</span>").appendTo(jqAnchor);
                    jqSpan.data('data-href', jsonItems[i].href);
                    jqSpan.click(navigateTo);
                }
                $('body').data('data-activeMenu', '');
                if ($('body').data('data-activeMenu') != '') {
                    alert('failed to clear data-activeMenu on Body');
                };
                //[Line 130 in fiddle screen]$('body').click(hideMenu)
                $('body').data('data-activeMenu', sMenuId);
                if ($('body').data('data-activeMenu') != sMenuId) {
                    alert('failed to set data-activeMenu on Body');
                };


                jqMenu.css('position', 'absolute');
                jqMenu.css('left', lPixelLeft + 'px');
                jqMenu.css('top', lPixelTop + 'px');
                jqMenu.css('display', 'block');
            } else {
                alert("menu (ul) id '" + sMenuId + "' not found!");
            }

        } else {
            alert("menu id '" + sMenuId + "' is null!");
        }
    }

    function wireUpButton() {
        var sButtonId = '#button_ShowMenu';
        var buttonMoveList = $(sButtonId);
        if (buttonMoveList) {
            buttonMoveList.click(function () {
                setMenuInner('my_custom_menu', 400, 100, dynamicMenu());
            });
        } else {
            alert("button element id '" + sButtonId + "' not found!");
        }


    };
});
马克西米利安·劳梅斯特(Maximillian Laumeister)

首先,jsFiddle定义您的hideMenu函数为时已晚,因为jsFiddle默认情况下在加载时运行JavaScript。我将JSFiddle选项更改为“ no wrap-in head”,它开始正常工作。其次,我使用此答案中的代码创建了在菜单外单击时关闭菜单的功能

工作现场演示:

function hideMenu() {
    console.log("hideMenu entered");
    var sMenuId = $('body').data('data-activeMenu');
    if (sMenuId !== '') {
        var jqMenu = $('#' + sMenuId);

        if (jqMenu) {
            jqMenu.css('display', 'none');
        } else {
            alert("menu (ul) id '" + sMenuId + "' not found!");
        }
    } else {
        alert("menu id '" + sMenuId + "' is null!");
    }
}

$(document).ready(function () {

    $(document).mouseup(function (e)
    {
        var container = $("#my_custom_menu");

        if (!container.is(e.target) // if the target of the click isn't the container...
            && container.has(e.target).length === 0) // ... nor a descendant of the container
        {
            container.hide();
        }
    });
    
    wireUpContextMenu('#planetmap_AreaVenus');
    wireUpButton();
    //alert("run");

    function dynamicMenu() {
        var fruits = [{
            itemText: "Apple",
            href: "http:\/\/images.clipartpanda.com\/teacher-apple-clipart-apple-clipartclipart---simple-red-apple-3e7q8rci.png"
        }, {
            itemText: "Orange",
            href: "http:\/\/www.google.com"
        }, {
            itemText: "Banana",
            href: "http:\/\/www.bbc.co.uk"
        }, {
            itemText: "Grape",
            href: "http:\/\/www.hotmail.com"
        }];
        return fruits;
    }


    function wireUpContextMenu(elementId) {
        var elementForMenuLaunch = $(elementId);
        if (elementForMenuLaunch) {
            elementForMenuLaunch.bind('contextmenu', function (e) {
                e.preventDefault();
                var lPixelLeft = this.offsetLeft;
                var lPixelTop = this.offsetTop;
                setMenuInner('my_custom_menu', lPixelLeft, lPixelTop, dynamicMenu());
                
                //alert('The eventhandler will make sure, that the contextmenu doesn\'t appear.');
            });

        } else {
            alert("elementForMenuLaunch '" + elementId + "'is not found!");
        }
    };

    function navigateTo(e) {
        console.log("hideMenu entered");
        hideMenu();
        var href = jQuery.data(this, 'data-href');
        console.log("called navigateTo " + href);
        window.location.href = href;  
    }




    function setMenuInner(sMenuId, lPixelLeft, lPixelTop, jsonItems) {
        //console.log("setMenu entered");
        if (sMenuId !== '') {
            var jqMenu = $('#' + sMenuId);

            if (jqMenu) {
                jqMenu.empty();


                //jQuery.data(document.body, 'data-activeMenu', sMenuId);

                //hideMenu();
                //$('body').click(hideMenu());

                var lItemCount = jsonItems.length;
                for (var i = 0; i < lItemCount; i++) {
                    var jqListItemNew = $("<li data-href='" + jsonItems[i].href + "'></li>").appendTo(jqMenu);
                    var jqAnchor = $("<a href='#'></a>" ).appendTo(jqListItemNew);
                    var jqSpan = $("<span data-href='" + jsonItems[i].href + "'>" + jsonItems[i].itemText + "</span>").appendTo(jqAnchor);
                    jqSpan.data('data-href', jsonItems[i].href);
                    jqSpan.click(navigateTo);
                }
                $('body').data('data-activeMenu', '');
                if ($('body').data('data-activeMenu') != '') {
                    alert('failed to clear data-activeMenu on Body');
                };
                //$('body').click(hideMenu)
                $('body').data('data-activeMenu', sMenuId);
                if ($('body').data('data-activeMenu') != sMenuId) {
                    alert('failed to set data-activeMenu on Body');
                };


                jqMenu.css('position', 'absolute');
                jqMenu.css('left', lPixelLeft + 'px');
                jqMenu.css('top', lPixelTop + 'px');
                jqMenu.css('display', 'block');
            } else {
                alert("menu (ul) id '" + sMenuId + "' not found!");
            }

        } else {
            alert("menu id '" + sMenuId + "' is null!");
        }
    }

    function wireUpButton() {
        var sButtonId = '#button_ShowMenu';
        var buttonMoveList = $(sButtonId);
        if (buttonMoveList) {
            buttonMoveList.click(function () {
                setMenuInner('my_custom_menu', 400, 100, dynamicMenu());
            });
        } else {
            alert("button element id '" + sButtonId + "' not found!");
        }


    };
});
.context-menu {
    /*position: absolute;*/
    display: block;
    background-color: #f2f2f2;
    border-radius: 4px;
    font-family: Arial, sans-serif;
    font-size: 14px;
    min-width: 150px;
    border: 1px solid #d4d4d4;
    z-index:1200;
    list-style-type: none
}
.context-menu ul {
    list-style-type: none;
    margin: 4px 0px;
    padding: 0px;
    cursor: default;
}
.context-menu ul li {
    padding: 4px 16px;
}
.context-menu ul li:hover {
    background-color: #4677f8;
    color: #fefefe;
}

a:hover, a:hover span {
    color:#9A1A4A;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
    <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
    <script src="JavaScript1.js"></script>
    <img id="planets" src="http://www.w3schools.com/tags/planets.gif" usemap="#planetmap">
    <map name="planetmap" width="145" height="126" alt="Planets">
        <area id="planetmap_AreaSun" shape="rect" coords="0,0,82,126" href="http://www.w3schools.com/tags/sun.htm" alt="Sun">
        <area id="planetmap_AreaMercury" shape="circle" coords="90,58,3" href="http://www.w3schools.com/tags/mercur.htm" alt="Mercury">
        <area id="planetmap_AreaVenus" shape="circle" coords="124,58,8" href="http://www.w3schools.com/tags/venus.htm" alt="Venus">
    </map>
    <table>
        <tr>
            <td>
                <ul class="context-menu" id="my_custom_menu" style="display:none;">
                    <!--style="display:none;"-->
                    <li>Strawberry</li>
                    <li>Raspberry</li>
                </ul>
            </td>
        </tr>
    </table>
        <!--<button id="button_ShowMenu2" onclick="setMenu('my_custom_menu', this, dynamicMenu())" type="button">Show Menu</button> -->
        <button id="button_ShowMenu" type="button">Show Menu</button>
        <button id="button_HideMenu" onclick="hideMenu()" type="button">Hide Menu</button>

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

超时后如何关闭上下文菜单?

来自分类Dev

超时后如何关闭上下文菜单?

来自分类Dev

用户单击其他图钉时如何关闭上一个信息窗口?

来自分类Dev

当用户单击页面其他位置时如何关闭自定义下拉菜单

来自分类Dev

使用mat-menu作为上下文菜单:如何关闭打开的mat-menu,然后在其他位置打开

来自分类Dev

在用户单击复选框后保持上下文菜单打开?

来自分类Dev

单击上下文菜单时如何启动意图活动?

来自分类Dev

如何在单击鼠标左键时显示WebBrowser控件上下文菜单

来自分类Dev

如何在单击鼠标左键而不是单击鼠标右键时打开D3.js上下文菜单

来自分类Dev

如何在单击鼠标左键而不是单击鼠标右键时打开D3.js上下文菜单

来自分类Dev

在Java EE中隐式关闭上下文

来自分类Dev

完成并关闭上下文后,如何查看Spark作业的日志?

来自分类Dev

用户单击其他位置时,如何隐藏导航栏的下拉菜单?

来自分类Dev

防止 Spring 在初始化上下文后关闭上下文

来自分类Dev

单击上下文菜单时打开扩展弹出窗口

来自分类Dev

上下文菜单显示下次单击时的更改

来自分类Dev

如何在WPF中订阅上下文菜单关闭事件?

来自分类Dev

触发上下文菜单,单击Microstrategy + Javascript

来自分类Dev

Javascript:检测左键单击打开的上下文菜单

来自分类Dev

如何在TableView rowDelegate中单击鼠标右键显示上下文菜单

来自分类Dev

如何在Chrome的信息亭模式下右键单击/长按禁用上下文菜单?

来自分类Dev

左键单击如何在QSystemTrayIcon中显示上下文菜单

来自分类Dev

如何在TableView rowDelegate中单击鼠标右键显示上下文菜单

来自分类Dev

如何在Windows 10中禁用右键单击上下文菜单?

来自分类Dev

如何在窗口10的右键单击上下文菜单中添加cmd删除选项

来自分类Dev

C# 如何在上下文子菜单上动态添加单击事件

来自分类Dev

如何在VueJS上下文中单击取消按钮关闭vs-popup

来自分类Dev

上下文菜单MenuItem单击“数据上下文”?

来自分类Dev

打开一个菜单时隐藏所有其他上下文菜单

Related 相关文章

  1. 1

    超时后如何关闭上下文菜单?

  2. 2

    超时后如何关闭上下文菜单?

  3. 3

    用户单击其他图钉时如何关闭上一个信息窗口?

  4. 4

    当用户单击页面其他位置时如何关闭自定义下拉菜单

  5. 5

    使用mat-menu作为上下文菜单:如何关闭打开的mat-menu,然后在其他位置打开

  6. 6

    在用户单击复选框后保持上下文菜单打开?

  7. 7

    单击上下文菜单时如何启动意图活动?

  8. 8

    如何在单击鼠标左键时显示WebBrowser控件上下文菜单

  9. 9

    如何在单击鼠标左键而不是单击鼠标右键时打开D3.js上下文菜单

  10. 10

    如何在单击鼠标左键而不是单击鼠标右键时打开D3.js上下文菜单

  11. 11

    在Java EE中隐式关闭上下文

  12. 12

    完成并关闭上下文后,如何查看Spark作业的日志?

  13. 13

    用户单击其他位置时,如何隐藏导航栏的下拉菜单?

  14. 14

    防止 Spring 在初始化上下文后关闭上下文

  15. 15

    单击上下文菜单时打开扩展弹出窗口

  16. 16

    上下文菜单显示下次单击时的更改

  17. 17

    如何在WPF中订阅上下文菜单关闭事件?

  18. 18

    触发上下文菜单,单击Microstrategy + Javascript

  19. 19

    Javascript:检测左键单击打开的上下文菜单

  20. 20

    如何在TableView rowDelegate中单击鼠标右键显示上下文菜单

  21. 21

    如何在Chrome的信息亭模式下右键单击/长按禁用上下文菜单?

  22. 22

    左键单击如何在QSystemTrayIcon中显示上下文菜单

  23. 23

    如何在TableView rowDelegate中单击鼠标右键显示上下文菜单

  24. 24

    如何在Windows 10中禁用右键单击上下文菜单?

  25. 25

    如何在窗口10的右键单击上下文菜单中添加cmd删除选项

  26. 26

    C# 如何在上下文子菜单上动态添加单击事件

  27. 27

    如何在VueJS上下文中单击取消按钮关闭vs-popup

  28. 28

    上下文菜单MenuItem单击“数据上下文”?

  29. 29

    打开一个菜单时隐藏所有其他上下文菜单

热门标签

归档