JavaScript使用视口宽度/高度计算

Tob*_*Alt 10 javascript css viewport

我试图在我的移动Webview中设置响应点并执行此操作:

var w = window.innerWidth-40;
var h = window.innerHeight-100;
Run Code Online (Sandbox Code Playgroud)

到目前为止,这很有用.但值-40和-100不在视口缩放高度和宽度中.

当我这样做:

var w = window.innerWidth-40vw;
var h = window.innerHeight-100vh;
Run Code Online (Sandbox Code Playgroud)

因为它应该保持响应和相对于视口 - JS不再工作.我认为vh和vw只适用于CSS?我怎样才能在JS中实现这一目标?

请求没有JQuery解决方案 - 只有JS!

谢谢

Yas*_*asi 16

基于此站点,您可以编写以下函数javascript来计算所需的值:

function vh(v) {
  var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
  return (v * h) / 100;
}

function vw(v) {
  var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
  return (v * w) / 100;
}

function vmin(v) {
  return Math.min(vh(v), vw(v));
}

function vmax(v) {
  return Math.max(vh(v), vw(v));
}
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));
Run Code Online (Sandbox Code Playgroud)

我在代码中使用了这个令人难以置信的问题!


小智 5

尝试这个:

function getViewport() {

 var viewPortWidth;
 var viewPortHeight;

 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
 if (typeof window.innerWidth != 'undefined') {
   viewPortWidth = window.innerWidth,
   viewPortHeight = window.innerHeight
 }

// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
 else if (typeof document.documentElement != 'undefined'
 && typeof document.documentElement.clientWidth !=
 'undefined' && document.documentElement.clientWidth != 0) {
    viewPortWidth = document.documentElement.clientWidth,
    viewPortHeight = document.documentElement.clientHeight
 }

 // older versions of IE
 else {
   viewPortWidth = document.getElementsByTagName('body')[0].clientWidth,
   viewPortHeight = document.getElementsByTagName('body')[0].clientHeight
 }
 return [viewPortWidth, viewPortHeight];
}
Run Code Online (Sandbox Code Playgroud)

参考: http: //andylangton.co.uk/articles/javascript/get-viewport-size-javascript/