嵌套的iframe页面中rem字号变小问题处理

问题原因

如果 html 的 font-size: 100px,那字号为0.16rem的字实际为100px * 0.16 = 16px

最外层的html的字号
在这里插入图片描述
iframe下的html字号
在这里插入图片描述
不相同时,则会导致iframe页面内的字体字号存在问题

解决办法

先获取外层html的font-size

const fontSize = parseFloat(window.getComputedStyle(document.documentElement).fontSize); // 外层HTML的font-size值

方案一,同源情况下

const currentIframe = document.getElementById('IframeRef');
const currentDoc = currentIframe.contentDocument || currentIframe.contentWindow.document; // 非同源会在contentWindow.document报错
const htmlElement = currentDoc.getElementsByTagName("html");
htmlElement.style.fontSize = fontSize + 'px';

方案二,非同源情况下

运用postMessage向iframe内页面传递消息

父页面发生消息

setTimeout(() => {
	const iframeElement = document.getElementById('IframeRef');
	iframeElement.onload = function () {
	  iframeElement.contentWindow.postMessage(
	    JSON.stringify({
	      event: 'design-font',
	      param: {
	        fontSize: fontSize + 'px',
	      },
	    }),
	    '*' // targetOrigin,通过窗口的 origin 属性来指定哪些窗口能接收到消息事件,其值可以是字符串"*"(表示无限制)或者一个 URL
	  );
	};
}, 300);

iframe内的子页面接受消息

window.addEventListener('message', e => {
    // e.data为父页面发送的数据
    const data = JSON.parse(e.data);
    switch (data.event) {
    	case 'design-font':
    		document.documentElement.style.fontSize = (data.param ? data.param.fontSize : 0) || "100px";
    		break;
    	... // 其他消息
    }
    
}, false)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值