【发布时间】:2020-03-06 13:39:51
【问题描述】:
无论平台如何,我都需要一个 svg 来始终匹配屏幕的高度。 我在 css 中选择 svg 并将高度设置为 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>
所以这将每 10 秒检查一次窗口大小的变化,然后使 svg 与大小匹配。
请告诉我有更好的方法。
【问题讨论】:
-
希望我理解正确。在这种情况下,您不需要 javascript。添加
svg{width:100vw; height:100vh;}。默认情况下,svg 强制统一缩放,圆圈将始终保持在 svg 画布的中间。或者,您可以尝试将preserveAspectRatio="xMidYMid slice"添加到 svg 元素。这将强制进行统一缩放,但会切掉那些落在外面的图像部分。
标签: javascript html css svg responsive-design