我从here改编了一些代码,以检测我的Phonegap应用程序中的方向变化(以加载横向和纵向的不同CSS文件)。我收到“无法读取null错误的属性'content',这意味着DOM调用有问题。代码涉及将以下psuedo元素添加到主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*/

最佳答案

似乎bodyAfterStyle丢失了,我建议将其分配移到事件函数中。

10-02 09:06
查看更多