【问题标题】:CSS expression for tablet device width平板设备宽度的 CSS 表达式
【发布时间】:2012-07-20 07:31:57
【问题描述】:

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

【问题讨论】:

    标签: css css-expressions


    【解决方案1】:

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

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

    您还可以尝试更多细节 - 这些将被视为 hack(感谢 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});
    }
    

    我还没有测试过这些,但我认为它会起作用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-30
      • 1970-01-01
      • 2016-08-16
      • 2011-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-08
      相关资源
      最近更新 更多