我想在浏览器调整按钮大小后将按钮的高度与外部 SVG 的高度联系起来。
Jsfiddle在这里。
下面是脚本:
function svgLoad() {
"use strict";
this.wrapper = document.getElementById('wrapper');
this.navID = document.querySelector('#slideMenu');
this.menuButton = document.querySelector('#menuButton');
this.logo = document.getElementById('logo');
this.logoWrap = document.getElementById('logoWrap');
this.navBar = document.getElementById('navBarWrap');
console.log(this.logo);
console.log(this.logo.clientHeight);
console.log(this.navBar.clientHeight);
this.loaded = function() {
this.logoHeight = Math.round(this.logo.clientHeight);
this.rect = this.logo.getBoundingClientRect();
console.log(this.rect.height);
console.log(this.logoHeight);
console.log(this.navBar.clientHeight);
// Sets height of menu button to match height of logo.
this.menuButton.style.height = this.logoHeight + 'px';
console.log(this.menuButton.style.height);
this.wrapper.style.marginTop = this.navBar.clientHeight + 'px';
}.bind(this);
this.logo.onload = this.loaded;
}
new svgLoad();
如果我使用 window.onload,一切显示正常,但我希望在 SVG 准备就绪后运行脚本。如果我尝试在加载 SVG 对象时运行,我会在浏览器上得到不同的结果。
在FF和Edge/IE中使用SVG上的onload/addEventListener一切正常。
在Chrome中,它根本不起作用,它始终将SVG的大小报告为160px。它在控制台中将 SVG 显示为匿名函数,并且在其中正确计算客户端高度;它只是不会将其应用于脚本(可能值得注意的是,即使它在 Chrome 中根本没有加载 SVG,它也会在小提琴中报告相同的高度(。
编辑 - 经过更多的研究,Chrome似乎正在更改SVG的offsetTop属性,以弥补它应该在dsisplay的高度和160px之间的差异。
我一直在玩这个并找到了答案。
FF 和 IE/Edge 将正确调整 SVG 的大小,而无需在对象上指定宽度或高度。Chrome 要求先指定高度,然后才能将正确的客户端高度发送到脚本。
就我而言,使用 rem/em 是最好的解决方案。