我试图在我的移动 Webview 中设置一个响应点并这样做:
var w = window.innerWidth-40;
var h = window.innerHeight-100;
目前效果很好。但值 -40 和 -100 不在视口(viewport)缩放高度和宽度中。
当我这样做时:
var w = window.innerWidth-40vw;
var h = window.innerHeight-100vh;
因为它应该保持响应并相对于视口(viewport) - JS 不再工作。 我认为 vh 和 vw 只适用于 CSS? 我怎样才能在 JS 中实现这一点?
请不要使用 JQuery 解决方案 - 只有 JS!
谢谢
最佳答案
基于 this site您可以使用以下实用程序函数来计算您想要的值作为屏幕宽度或高度百分比的函数:
function vh(percent) {
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
return (percent * h) / 100;
}
function vw(percent) {
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
return (percent * w) / 100;
}
function vmin(percent) {
return Math.min(vh(percent), vw(percent));
}
function vmax(percent) {
return Math.max(vh(percent), vw(percent));
}
console.info(vh(20), Math.max(document.documentElement.clientHeight, window.innerHeight || 0));
console.info(vw(30), Math.max(document.documentElement.clientWidth, window.innerWidth || 0));
console.info(vmin(20));
console.info(vmax(20));
我用了this我的代码中令人难以置信的问题!
关于JavaScript 计算视口(viewport)宽度/高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44109314/