javascript - 如果在 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;">
如果我将删除此边距,它也会在第一次点击时正确计算。
我无法删除正文边距。有什么办法可以解决这个问题?
解决方案
从您发布的内容来看,它看起来像是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
事件上。
推荐阅读
- php - 如何在 Codeception 的 Stub 对象中测试方法的参数?
- excel - DXL 脚本 - 如果存在于任何单元格中,则将图像从 Excel 单元格导入到 Doors
- nginx - Kubernetes 中的 SPRING_CLOUD_CONFIG_URI 设置
- mermaid - 用斜体渲染一个抽象类(美人鱼的类图)
- javascript - 如何在 cypress 中按名称运行单个测试?
- swift - 从本地仓库添加包失败
- c++ - 我使用什么模板参数?(C++ 概念问题)
- parameters - 参数 () 与 SpreadsheetApp.Sheet.getRange 的方法签名不匹配
- flutter - 无法通过浏览器的 ctrl+F 搜索文本,使用 CanvasKit Flutter
- linux - ShellScript 中的动态变量分配 - 如何?