首页 > 解决方案 > 如果在 IE 中的 body 元素上使用边距,则 Jquery 偏移量未给出预期值

问题描述

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

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

我试图将 aContextMenu定位如下:-

$(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" },
        }
    });
});

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>

IE 11一旦页面加载,一旦我点击 td id jquery.ui.positiontdMenu不会正确计算偏移量。在第二次点击它计算正确。

我发现在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.
    };
}

我也给身体留出了余地:-

<body style="margin: 0px;">

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

我无法删除正文边距。有什么办法可以解决这个问题?

标签: javascriptjqueryhtmlcsscontextmenu

解决方案


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

更换

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

  $.contextMenu({/* your stuff here */})
});

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

  $.contextMenu({/* your stuff here */ })
});

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


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

function cMenu() {
    $.contextMenu({
      /* your stuff here */ 
    });
}
$(document).ready(cMenu);
$(window).on('load', cMenu);

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


推荐阅读