浏览器不会自动更改图像

时间:2014-04-15 16:59:49

标签: android

我为肖像和风景创建了两个背景图像,我想在客户端旋转屏幕时自动更改背景图像。不幸的是,它没有像我想的那样工作......

<script>
    var stage = document.getElementById('stage');

    var width = screen.width;
    var height = screen.height;

    stage.style.width = width + 'px';
    stage.style.height = height + 'px';

    if (width < height) {
      // portrait
      stage.style.background = 'url(portrait.png) no-repeat';
    } else {
      // landscape
      stage.style.background = 'url(landscape.png) no-repeat';
    }

    var supportsOrientationChange = "onorientationchange" in window,
    orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

    window.addEventListener(orientationEvent, function() {

        if (screen.width < screen.height) {
          // portrait
          stage.style.background = 'src(portrait.png) no-repeat';
          alert('Portrait');
        } else {
          // landscape
          stage.style.background = 'src(landscape.png) no-repeat';
          alert('Landscape');
        }

    }, false);

</script>
你能帮我改进吗?

1 个答案:

答案 0 :(得分:0)

您可以将CSS3媒体查询用于特定方向的样式。

/* Portrait */
@media screen and (orientation:portrait) {
    /* Portrait styles */
}
/* Landscape */
@media screen and (orientation:landscape) {
    /* Landscape styles */
}