最近需要把一个web后台项目进行移动端适配 , 其中有个需求是需要把数据图表部分可以自由切换横竖屏展示
核心代码如下:
// needRotate为全局变量, 用于横竖屏判断
window.addEventListener("orientationchange", event => {
if (window.orientation == 90) {
this.needRotate = true;
} else {
this.needRotate = false;
}
if (document.getElementById("showBigChart")) {
// 此处需要摧毁echart已建立好的实例 , 可以通过移除 "_echarts_instance_" 属性令echart重新建立图表
document
.getElementById("showBigChart")
.removeAttribute("_echarts_instance_");
const mychart = echarts.init(document.getElementById("showBigChart"));
if (this.needRotate) {
this.echartConfigs = {
// 减的部分是我项目内的样式适配, 可根据实际情况修改
width: document.body.offsetWidth - 100,
height: document.body.offsetHeight - 50
};
// 直接resize即可旋转图表
mychart.resize(this.echartConfigs);
} else {
this.echartConfigs = {
width: document.body.offsetWidth,
height: document.body.offsetHeight
};
mychart.resize(this.echartConfigs);
}
mychart.setOption(this.echartOptions, true);
console.log(document.body.offsetWidth,document.body.offsetHeight,this.echartConfigs)
}
});
主要应用到的属性为:
- window.orientation , 可以返回当前设备的方向 , 返回值为90时为横屏 (注意: 在chrome浏览器内的返回值与ios中相反 , 在安卓中也与ios相反)
- orientationchange , 监听设备的方向改变