如果在IE中的body元素上使用margin,则jQuery offset不会给出期望的值

Afn*_*mad 9 html javascript css jquery contextmenu

我试图设置a的位置contextMenu并使用Jquery jquery.ui.position。因为ContextMenu我正在使用此libaray:-

https://swisnl.github.io/jQuery-contextMenu/demo

我正在尝试将a ContextMenu定位如下:

$(document).ready(function() {

    $.contextMenu({
        selector: 'td[id="tdMenu"]',
        trigger: 'left',
        position: function (opt, x, y) {

            try {

                opt.$menu.position({
                    my: 'right top',
                    at: 'right bottom',
                    of: $("#tdDiv")
                });

            } catch (e) {

            }

        },
        items: {

            "0": { name: "Hi" },
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

HTML如下:

<table border="0" cellpadding="0" cellspacing="0" width="100%">
        <tr>
            <td id="tdDiv" style="background-color: yellow;">
                Menu Div
            </td>
        </tr>
         <tr>
            <td id="tdMenu">
                Click Here
            </td>
        </tr>
    </table>
Run Code Online (Sandbox Code Playgroud)

IE 11一次,页面将加载,并且一旦我单击ID为tdMenujquery.ui.position的td,就无法正确计算偏移量。在第二次单击它正确计算。

我发现的是在jquery.ui.position其内部计算偏移量,如下所示:

function getDimensions( elem ) {
    var raw = elem[0];
    return {
        width: elem.outerWidth(),
        height: elem.outerHeight(),
        offset: elem.offset() // On first click its calculating wrong value and on second it calculates correctly.
    };
}
Run Code Online (Sandbox Code Playgroud)

我也给身体留出以下余地:

<body style="margin: 0px;">
Run Code Online (Sandbox Code Playgroud)

如果我要删除此边距,它也会在第一次单击时正确计算。

我无法消除身体的边缘。为此可以采取什么措施?

And*_*hiu 2

从您发布的内容来看,这看起来像是在页面完成加载所有样式和内容之前计算值的经典案例,导致初始化offset时出现错误的偏移值。contextMenu

更换

$(document).ready(function() {
  // executes when DOM parser reaches </html> tag

  $.contextMenu({/* your stuff here */})
});
Run Code Online (Sandbox Code Playgroud)

$(window).on('load', function() {
  // executes when all external resources/references (images, scripts,
  // stylesheets, iframes, etc...) have finished loading

  $.contextMenu({/* your stuff here */ })
});
Run Code Online (Sandbox Code Playgroud)

可能会解决您的问题,但如果没有最小的、完整的和可验证的示例,就不可能测试并确保它适用于您的情况。


注意:上述解决方案将延迟初始化,$.contextMenu()直到页面加载完毕。如果您的页面需要很长时间才能加载其所有资源,并且您希望$.contextMenu在此之前进行初始化,则解决方法是将其初始化$(document).ready并更新$(window).load

$(document).ready(function() {
  // executes when DOM parser reaches </html> tag

  $.contextMenu({/* your stuff here */})
});
Run Code Online (Sandbox Code Playgroud)

实际上,页面中很可能只有一项会影响该偏移量(很可能是样式表)。如果您是哪一个(通过消除,禁用页面中的内容),您甚至不必等待其余部分加载,您可以简单地将函数的重新运行绑定到该元素的事件上onload