我刚刚注意到,如果我在一个标签页中放大网页(通过按下Ctrl-Plus),然后打开我的Chrome扩展的弹出窗口,它也会被放大。不幸的是,这使得它显示垂直滚动条,并且在更大的缩放比例下,甚至还有水平滚动条。
我看到其他扩展程序以某种方式通过仅以100%缩放显示其弹出窗口来阻止此缩放。问题是如何做到这一点?
我刚刚注意到,如果我在一个标签页中放大网页(通过按下Ctrl-Plus),然后打开我的Chrome扩展的弹出窗口,它也会被放大。不幸的是,这使得它显示垂直滚动条,并且在更大的缩放比例下,甚至还有水平滚动条。
我看到其他扩展程序以某种方式通过仅以100%缩放显示其弹出窗口来阻止此缩放。问题是如何做到这一点?
对于对我解决此问题感兴趣的人,以下是我的解决方案。
首先,我了解到一个关于Chrome的小细节。要放大插件的弹出窗口,需要从Chrome的“设置”中打开其“选项”窗口并进行缩放。然后,即使关闭了“选项”页面,相应的插件也将保留缩放设置。要恢复它,只需在“选项”页面上恢复缩放即可。很酷,对吧!不过很遗憾,许多插件无法正确处理它。正如我在原始问题中提到的那样,大多数显示奇怪的滚动条或者简单地扭曲内容。
以下是我在插件中克服这个问题的方法:
首先,您需要确定弹出窗口的当前缩放比例。(以下仅在Chrome上测试,摘自此帖子):
function getPageZoom()
{
//RETURN: 1.0 for 100%, and so on
var zoom = 1;
try
{
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
svg.setAttribute('version', '1.1');
document.body.appendChild(svg);
zoom = svg.currentScale;
document.body.removeChild(svg);
}
catch(e)
{
console.error("Zoom method failed: " + e.message);
}
return zoom;
}
然后创建一个可滚动的 DIV
,将您的弹出窗口内容放在其中,并确保它可以滚动:
#mainSection{
margin: 0;
padding: 0;
overflow-y: auto; /* The height will be defined in JS */
}
<div id="mainSection">
</div>
然后使用页面缩放的小比例计算来设置可滚动的DIV
的最大高度。尽早在DOM加载时这样做,例如从onLoad()
事件中,或在jQuery的$(function(){});
中:
//Get page zoom
var zoom = getPageZoom();
//Using jQuery
var objMain = $("#mainSection");
//Calculate height & offsets of elements inside `mainSection`
//using jQuery's offset() and outerHeight()
//Make sure to multiply results returned by zoom
var offsetElement1 = $("someElement1").offset().top * zoom;
var heightElement2 = $("someElement2").outerHeight() * zoom;
//Apply the calculations of the height (in real situation you'll obviously do more...)
var height = offsetElement1 + heightElement2;
//And finally apply the calculated height by scaling it back down
var scaledHeight = height / zoom;
//Need to convert the result to an integer
scaledHeight = ~~scaledHeight;
//And set it
objMain.css("max-height", scaledHeight + 'px');
$(window).resize(function()
{
var zoom = getPageZoom();
//Multiply zoom by 100 (to round it to 2 decimal points) and convert to int
var iZoom = zoom * 100;
iZoom = ~~iZoom;
if(window.izoom &&
iZoom != window.izoom)
{
//Close popup
window.close();
}
window.izoom = iZoom;
});
<meta name="viewport" content="width=device-width, initial-scale=1.0">
,但好像没有任何作用。有趣的是,如果我的扩展选项页面被缩放了,似乎缩放只适用于我的扩展。 - c00000fd