无论您使用哪种设备或屏幕尺寸,如何使svg高度都与屏幕高度匹配

无论平台如何,我都需要一个svg来始终匹配屏幕的高度。 我在CSS中选择svg,并将height设置为100%或height:100vh或min-height:100vh以及大约10个其他组合。但是当我在设备工具栏上摆弄它时,总是可以找到它无法使用的设备。

尤其是Ipad。

所以我感到绝望,并使用了“ onResize”事件,并使用javascript使用window.innerHeight将svg的高度设置为屏幕的高度。

但是显然onResize是有问题的,并且当它调整大小时,屏幕的初始大小在长达一到两秒钟内是错误的。 所以我很鄙视,并写下了这个怪诞的故事。 (虽然有效)

let oldSize = 0; //keeps track of what the size was
function size() {

  if (window.innerHeight != oldSize) { //if the height does not match the old height do something
    oldSize = window.innerHeight; //set the old height to the new height
    $('svg').attr('height',window.innerHeight); //set the height of the svg to the new height
  }
  setTimeout(size,100); //wait a 10th of a second and try again.
}
size(); //start the recursive loop of desparation.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<svg viewBox="0 0 100 100">
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>

因此,这将每隔十分之一秒检查一次窗口大小的变化,然后使svg匹配大小。

请告诉我有一种更好的方法。

zylan131415 回答:无论您使用哪种设备或屏幕尺寸,如何使svg高度都与屏幕高度匹配

您可以在窗口调整大小事件上添加事件侦听器,而不是每100毫秒调用一次函数:

let oldSize = 0; //keeps track of what the size was

function size() {
  console.log('Resized!');
  if (window.innerHeight != oldSize) { //if the height does not match the old height do something
    oldSize = window.innerHeight; //set the old height to the new height
    $('svg').attr('height',window.innerHeight); //set the height of the svg to the new height
  }
}

window.addEventListener('resize',size);

size();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<svg viewBox="0 0 100 100">
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>

本文链接:https://www.f2er.com/3128058.html

大家都在问