Skip to main content

加载网页旋转方向

需求描述

客户提出需求,想加载网页的时候能够指定方向,为了适配不同方向放置的设备(比如倒挂的电视),下面是用iframe实现的思路,我们把网页加载到iframe中,然后根据传入的方向进行旋转。

实现代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="renderer" content="webkit">
<title>Document</title>
<style>
html,body {
margin: 0;
padding: 0;
background: #ffffff;
width: 100% !important;
height: 100% !important;
}

body>iframe {
border: none;
position: fixed;
top: 0;
left: 0;
}
</style>
</head>
<body>

</body>
</html>
<script>
let url = "https://www.baidu.com/"
let direction = "bottom"

window.onload = function () {
if (["#left", "#top", "#right", "#bottom"].includes(window.location.hash)) {
direction = window.location.hash.substring(1)
}

let clientWidth = document.body.clientWidth
let clientHeight = document.body.clientHeight

console.log('clientWidth', clientWidth)
console.log('clientHeight', clientHeight)

let width = document.body.clientWidth
let height = document.body.clientHeight
let rotate = 0
let offset = 0

if (direction === "left") {
width = document.body.clientHeight
height = document.body.clientWidth
offset = parseInt((width - height) / 2)
rotate = 90

} else if (direction === "right") {
width = document.body.clientHeight
height = document.body.clientWidth
offset = parseInt((width - height) / 2)
rotate = 270

} else if (direction === "top") {
rotate = 180
}

let iframe = document.createElement('iframe')
iframe.src = url
iframe.style = "-webkit-transform: rotate("+(rotate)+"deg) !important;transform:rotate("+rotate+"deg) !important;left:"+(-offset)+"px !important;top:"+(offset)+"px !important;width: "+(width)+"px;height:"+(height)+"px;"
document.body.appendChild(iframe)
}
</script>