![](/img/trans.png)
[英]How do I find the center of an image, and place another image on top of it?
[英]How properly calculate and place an image on top of another image when they're both scaled - cross browser?
我有一個基本圖片,上面有物品。 如果用戶禁用其中一項,則應顯示為已禁用。 為了解決這個問題,我使用了禁用項目的第二張圖像(png),並將其放置在背景圖像上方的正確位置。
如果沒有縮放比例,則可以在所有瀏覽器上完美運行。
當縮放時(例如,在移動瀏覽器中,圖像為原始大小的40%時) 僅在Firefox中有效 。 Firefox始終將圖像放置在正確的位置,覆蓋下面的項目。
其他瀏覽器(Android上的Chrome,Safari iOS)始終保持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中的bg”是純色時才有效。
僅在WebKit中會出現此問題,在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";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.