当用户在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);
}
}
答案 0 :(得分:1)
如果设备是横向或纵向,您可以使用CSS媒体查询来检测。使用CSS,您可以定义何时显示哪些信息。例如:
/* ----------- iPhone 6+ ----------- */
/* Portrait and Landscape */
@media only screen
and (min-device-width: 414px)
and (max-device-width: 736px)
and (-webkit-min-device-pixel-ratio: 3) {
/* Your styles */
}
/* Portrait */
@media only screen
and (min-device-width: 414px)
and (max-device-width: 736px)
and (-webkit-min-device-pixel-ratio: 3)
and (orientation: portrait) {
/* Your styles */
}
/* Landscape */
@media only screen
and (min-device-width: 414px)
and (max-device-width: 736px)
and (-webkit-min-device-pixel-ratio: 3)
and (orientation: landscape) {
/* Your styles */
}
有关更多示例,请参阅https://css-tricks.com/snippets/css/media-queries-for-standard-devices/。
答案 1 :(得分:0)