如果在IE中的body元素上使用了margin,Jquery偏移量没有给出预期值



我正在尝试设置contextMenu的位置,并使用Jqueryjquery.ui.position。对于ContextMenu,我使用这个库:-

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 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事件上。

删除contextMenu事件show之前的正文样式,并在activated事件之后重置正文样式。

你可以试试这样的东西:

$(document).ready(function() {
var bodystyle = '';
$.contextMenu({
selector: 'td[id="tdMenu"]',
trigger: 'left',
events: {
show : function(options){
bodystyle = $('body').attr('style');   
$('body').attr('style','');            
},
activated : function(options){
$('body').attr('style', bodystyle ) ;            
}
}
position: function (opt, x, y) {
try {
opt.$menu.position({
my: 'right top',
at: 'right bottom',
of: $("#tdDiv")
});
} catch (e) {
}
},
items: {
"0": { name: "Hi" },
}
});
});

最新更新