平板电脑设备宽度的CSS表达式



我需要用css表达式从css中找出并应用tablet宽度。我有一个div内容。它应该在纵向模式下应用100%的宽度,当我转向横向时,div应该将宽度更改为平板电脑设备宽度的一半(平板电脑宽度/2)。如何在css中应用此表达式方法?

我会尽量避开表达式,因为它们仅限于Internet Explorer 5、6和7(什么平板电脑运行这个??),而且它们会大大降低速度(性能方面)。无论如何,试试这个:

@media screen and (orientation:portrait) {
    /* Portrait styles */
}
@media screen and (orientation:landscape) {
    .element {
        width:expression(document.body.clientWidth / 2);
    }
}

你也可以尝试更多细节-这些将被视为黑客攻击(感谢TheBlackBenzKid的建议):

/* Windows 7 Phone - WP7 */
@media only screen and (max-device-width: 480px) and (orientation:portrait) {
}
@media only screen and (max-device-width: 480px) and (orientation:landscape) {
}
/* Apple iPhone */
@media only screen and (max-device-width: 320px) and (orientation:portrait) {
}
@media only screen and (max-device-width: 320px) and (orientation:landscape) {
}

如果不使用表达式(例如,针对其他浏览器和平板电脑),您可以使用一个小javascript来检测方向,然后在元素中添加一个类:

html:

<body onorientationchange="updateOrientation();">

Javascript:

function updateOrientation() {
    if(window.innerWidth> window.innerHeight){
        //we are in landscape mode, add the 'LandscapeClass' class to the element
        document.getElementById("element").className += " LandscapeClass";
    } else {
        //we are in portrait mode, remove the class
        document.getElementById("element").className = 
           document.getElementById("element").className.replace
              ( /(?:^|s)LandscapeClass(?!S)/ , '' );
}

如果使用jQuery,您可以尝试直接修改元素的(内联)CSS:

function updateOrientation() {
    var $width;
    if(window.innerWidth> window.innerHeight){
        $width = window.innerWidth/2;
    } else {
        $width = '100%';
    }
    $(".element").css({width:$width});
}

我还没有测试过这些,但我认为它会在

中工作

最新更新