送你一个封装的移动端横屏展示的JS库

2,071 阅读1分钟

前言

我们经常在移动端横屏展示一些东西,所以今天我们来介绍下怎么在移动端实现横屏展示。

效果

在这里插入图片描述

在这里插入图片描述

实现

源码:

// screenOrientation.js
export default function (option) {
	var _this = this;
	_this.option = {
		'mode': 'portrait', //portrait(竖屏)、landscape(横屏)
		'id': 'wrap', //最外层容器ID
		'init': false,
		'callback': false
	};
	for (var k in option)
		if (option[k] != '') _this.option[k] = option[k];
	var obj = document.getElementById(_this.option.id);
	var className = obj.className || " ";
	var w_width = obj.clientWidth;
	var w_height = obj.clientHeight;
	var flag = 0;
	var timer;
	if (_this.option.mode == "portrait")
		var cssBlock =
			'.' + _this.option.id + '_screenOrientation{-webkit-transform: rotateZ(-90deg) !important; transform: rotateZ(-90deg); position:relative;}';
	else
		// eslint-disable-next-line no-redeclare
		var cssBlock =
			'.' + _this.option.id + '_screenOrientation{-webkit-transform: rotateZ(90deg) !important; transform: rotateZ(90deg); position:relative;}';
	var style = document.createElement("style");
	style.type = "text/css";
	style.textContent = cssBlock;
	document.getElementsByTagName("head").item(0).appendChild(style);
	var _width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
	var _height = (window.innerHeight > 0) ? window.innerHeight : screen.height;
	_this.modifyDetec = function () {
		if ((_height < _width && _this.option.mode == "portrait") || (_height > _width && _this.option.mode == "landscape") && flag == 0) {
			obj.style.width = _height + "px";
			obj.style.height = _width + "px";
			obj.style.top = -(_width - _height) * 0.5 + "px";
			obj.style.left = -(_height - _width) * 0.5 + "px";
			obj.className = className + " " + (_this.option.id + "_screenOrientation");
			flag = 1;
			if (_this.option.callback) {
				_this.option.callback();
			}
		} else {
			obj.style.width = w_width + "px";
			obj.style.height = w_height + "px";
			obj.className = className;
			obj.style.top = " ";
			obj.style.left = " ";
			flag = 0;
		}
	}

	function detectOtt() {
		_width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
		_height = (window.innerHeight > 0) ? window.innerHeight : screen.height;
		if (window.orientation == 180 || window.orientation == 0 || window.orientation == 90 || window.orientation == -90) {
			clearTimeout(timer);
			timer = setTimeout(function () {
				_this.modifyDetec(_width, _height);
			}, 50);

		}
	}
	if (_this.option.init) {
		_this.option.init();
	}
	detectOtt();
	window.addEventListener("resize", detectOtt, false);

}

使用:

import screenOrientation from './screenOrientation.js'

// 方法
screen(){
  // portrait(竖屏)、landscape(横屏)
  // id : 最外层容器DOM元素ID
  new screenOrientation({ mode:'landscape', id:'wrap'})
}

结语


欢迎关注我的公众号「前端历劫之路」 ​

回复关键词电子书,即可获取近12本前端热门电子书。 ​

回复关键词红宝书第4版,即可获取最新《JavaScript高级程序设计》(第四版)电子书。 ​

你还可以加我微信,我拉拢了很多IT大佬,创建了一个技术交流、文章分享群,欢迎你的加入。 ​

  • 作者:Vam的金豆之路

  • 主要领域:前端开发

  • 我的微信:maomin9761

  • 微信公众号:前端历劫之路