我从这里改编了一些代码,以检测我的 Phonegap 应用程序中的方向变化(为横向和纵向加载不同的 CSS 文件)。我收到“无法读取属性‘内容’的空错误,这意味着 DOM 调用有问题。代码涉及将这些伪元素添加到主 CSS 文件中:
/*Orientation Detection Hack*/
body:after {
content: "";
position: absolute;
color: transparent;
}
@media all and (orientation: portrait) {
body:after {
content: "p";
}
}
@media all and (orientation: landscape) {
body:after {
content: "l";
}
}
/*end of orientation detection*/
这个事件监听器检查方向变化的伪元素:
/*ORIENTATION CHANGES*/
//get style of the body:after element
var bodyAfterStyle = window.getComputedStyle(document.body, ":after");
window.onorientationchange = function() {
navigator.notification.alert(
'ORIENTATION CHANGELOL', // message
'Credits', // title
'Credits'); // buttonName
if(bodyAfterStyle.content == 'p') {
/*whatever
navigator.notification.alert("Now in Portrait");
var sheet = document.createElement('link');
sheet.innerHTML = 'href=\"portrait.css\" rel=\"stylesheet\" type=\"text/css\"';
document.body.appendChild(sheet);
end whatever*/
}
else if(bodyAfterStyle.content == 'l') {
//do landscape stuff
}
}
/*END OF ORIENTATION STUFF*/