平板设备宽度的 CSS 表达式

标签 css css-expressions

我需要使用 css 表达式从 css 中找出并应用平板电脑宽度。 我有一个 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);
    }
}

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

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

关于平板设备宽度的 CSS 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11574847/

相关文章:

javascript - 滚动条在聊天框中不起作用?

css - 不寻常的圆 Angular 标记

javascript - CSS - 使用 Jquery 动态计算 IE11 的宽度

javascript - 设置 body 高度宽度css表达式

css - Alternative For Replacing CSS expression for IE10及以上版本

javascript - Facebook 样式命名约定

html - 居中左对齐的 Bootstrap 列,其中包含卡片

twitter-bootstrap - 无法在同一页面中使用两个 Bootstrap 模态

html - 避免 CSS 表达式

ruby-on-rails - 从 rails 隐藏字段中删除包装 div