需求是页面自适应浏览器大小展示不同数量数据
监听浏览器变化事件
通过 document.body.clientWidth 来获取到浏览器的宽,然后通过 window.addEventListener 来监听浏览器窗口的变化
1.在vue.js中先在data中定义自定义属性
data() {
return {
screenWidth: document.body.clientWidth, // 获取浏览器宽度
};
},
2.在monuted中调用resize监听方法,在 created 中 document 还未加载完成会监听不到
const that = this;
window.addEventListener('resize', () => {
that.screenWidth = window.screenWidth || document.body.clientWidth;
if (that.screenWidth < 1366) {
//执行...
} else {
//执行...
}
}, false);
3.考虑监听方法会在页面切换后继续执行浪费资源,需要在调用结束后销毁监听事件
beforeDestroy() {
window.removeEventListener('resize', {"需要结束的事件"}, false);
},
如此就可以监听到浏览器变化了。
iframe嵌套跨域问题
在当前项目中打开浏览器可以监听, 但在 iframe 中因为跨域层级不够, 父级宽度监听不到导致监听事件失效
1.使用 document.domain 来设置具有相同上级域名的属性
document.domain = 'xxx.com'; //xxx代表相同的上级域名
2.虽然 domain 现在设置了, 但是改变浏览器大小后发现监听事件不会实时监听, 需要监听到当前浏览器的最顶级宽度
//获取最顶级宽度,xxx代表引用iframe的最大div
window.parent.document.getElementById('xxx').clientWidth;
//if判断区分是否在iframe中
if (window.self !== window.top) {
that.screenWidth = window.parent.document.getElementById('xxx').clientWidth;
//执行...
} else {
that.screenWidth = window.screenWidth || document.body.clientWidth;
//执行...
}
如此就可解决iframe中跨域监听事件的问题。