我正在尝试设置 contextMenu
的位置并使用 Jquery jquery.ui.position
。对于 ContextMenu
我正在使用这个 libaray:-
https://swisnl.github.io/jQuery-contextMenu/demo
我正在尝试按以下方式定位 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" },
}
});
});
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
中,一旦页面加载并且我单击带有 id tdMenu
的 td jquery.ui.position 无法正确计算偏移量。第二次单击它会正确计算。
我发现在 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 留了余量:-
<body style="margin: 0px;">
如果我将删除此边距,它也会在第一次点击时正确计算。
我无法删除正文边距。解决这个问题的方法是什么?
最佳答案
从您发布的内容来看,它看起来像是计算 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 */ })
});
可能会解决您的问题,但没有 Minimal, Complete, and Verifiable example不可能测试并确保它适用于您的情况。
注意:上述方案会延迟$.contextMenu()
的初始化直到页面加载完毕。如果你的页面需要很长时间来加载它的所有资源并且你想要 $.contextMenu
在那一刻之前初始化,解决方法是在 $(document).ready
上初始化它并在 $(window).load
上更新它:
function cMenu() {
$.contextMenu({
/* your stuff here */
});
}
$(document).ready(cMenu);
$(window).on('load', cMenu);
实际上,页面中很可能只有一项会影响该偏移量(很可能是样式表)。如果你是哪一个(通过消除,禁用页面中的东西),你甚至不必等待其余部分加载,你可以简单地将你的函数的重新运行绑定(bind)到该元素'onload
上。事件。
关于javascript - 如果在 IE 中的 body 元素上使用边距,则 Jquery offset 不会给出预期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54303843/