【发布时间】:2015-04-25 22:33:18
【问题描述】:
当用户在 Web 应用程序上从纵向视图变为横向视图时,是否有一种处理方法?就像您在纵向视图中查看 Web 应用程序并看到正常数据一样。
然后,当您将设备转到横向视图时,您会看到一些不同的数据。
我的问题:有没有办法用纯 JavaScript 和 CSS 来完成这个?还是我必须依赖 API?
更新: 我找到了一种使用 Device Orientation API 使用纯/纯 JS 的方法,并且我找到了一个示例,它完成了我正在尝试做的事情,但我无法使其正常工作,因为 if 语句每次都打断我旋转大于 90 的时间,即使我放一个变量来检查旋转是否已经是 90。
function init() {
var compass = document.getElementById('compass'),
comp = document.getElementById("comp");
if(window.DeviceOrientationEvent) {
window.addEventListener('deviceorientation', function(event) {
var alpha;
//Check for iOS property
if(event.webkitCompassHeading) {
alpha = event.webkitCompassHeading;
//Rotation is reversed for iOS
compass.style.WebkitTransform = 'rotate(-' + alpha + 'deg)';
}
//non iOS
else {
alpha = event.alpha;
webkitAlpha = alpha;
if(!window.chrome) {
//Assume Android stock (this is crude, but good enough for our example) and apply offset
webkitAlpha = alpha-270;
}
}
compass.style.Transform = 'rotate(' + alpha + 'deg)';
//THIS IS THE PART I'VE ADDED
var iftrue = false;
comp.innerHTML = alpha + "deg";
if (alpha >= 90 && alpha <= 100) {
if (!iftrue) {
alert("it is");
return iftrue = true;
};
}
else if (alpha <= 90) {console.log("it is not");
};
//TILL HERE compass.style.WebkitTransform = 'rotate('+ webkitAlpha + 'deg)';
//Rotation is reversed for FF
compass.style.MozTransform = 'rotate(-' + alpha + 'deg)';
}, false);
}
}
【问题讨论】:
标签: javascript html css device-orientation