我有一个基本图像,上面有项目。如果用户禁用了其中一个项目,那么它应该显示为已禁用。为了处理这个问题,我使用了禁用项目的第二个图像(png),并将其放置在背景图像上方的正确位置。
当没有缩放时,这在所有浏览器中都能完美工作。
当存在缩放时(例如,在移动浏览器中,当图像为原始大小的40%时),此仅适用于Firefox。Firefox总是将图片放在正确的位置,覆盖下面的项目。
其他浏览器(Android上的Chrome、iOS上的Safari)总是关闭1-2像素,具体取决于缩放级别。所以你可以在下面看到一些项目。
我如何做到这一点,使其跨浏览器工作?
var heightRatio = bgOffsetHeight / originalHeight;
var widthRatio = bgOffsetWidth / originalWidth;
//Place the disabled items
for ( var i = 0; i < disableds.length; i++ )
{
var disabled = disableds[ i ];
/**
* I also tried with "parseInt", but it still doesn't work.
*
* originalLeft/Top/Width/Height are the values saved in
* JavaScript when the page is first loaded before everything
* is scaled.
*/
disabled.style.left = ( widthRatio * disabled.originalLeft ) + "px";
disabled.style.top = ( heightRatio * disabled.originalTop ) + "px";
disabled.style.width = ( widthRatio * disabled.originalWidth ) + "px";
disabled.style.height = ( heightRatio * disabled.originalHeight ) + "px";
//Make visible
disabled.style.visibility = "visible";
}
您的背景使用白色还是其他纯色?然后您可以尝试这样做:在bg部分上放置一个空div,然后应用background-color: rgba(255, 255, 255, .5)
。这应该会给你同样的效果,而且它会节省大量额外的图像。但只有当"你的bg"是纯色时才有效。
该问题仅出现在WebKit中,单独计算宽度和高度比会使浏览器无法正确调整图像大小和放置图像。如果我将代码更改为只使用宽度比,那么所有浏览器中的所有内容都会正确放置:
//We no longer use height ratio for the height/top calculations
//var heightRatio = bgOffsetHeight / originalHeight;
var widthRatio = bgOffsetWidth / originalWidth;
//Place the disabled items
for ( var i = 0; i < disableds.length; i++ )
{
var disabled = disableds[ i ];
/**
* I also tried with "parseInt", but it still doesn't work.
*
* originalLeft/Top/Width/Height are the values saved in
* JavaScript when the page is first loaded before everything
* is scaled.
*/
disabled.style.left = ( widthRatio * disabled.originalLeft ) + "px";
disabled.style.top = ( widthRatio * disabled.originalTop ) + "px";
disabled.style.width = ( widthRatio * disabled.originalWidth ) + "px";
disabled.style.height = ( widthRatio * disabled.originalHeight ) + "px";
//Make visible
disabled.style.visibility = "visible";
}