使用JavaScript根据页面大小获取不同的行为

时间:2012-02-07 14:46:04

标签: javascript jquery

我正在尝试根据一些提供缩放功能的JavaScript激活不同屏幕/浏览器分辨率的不同设置。我在HTML文档中包含了以下脚本,但我认为它的工作正常。

我所说的是,如果屏幕宽度超过1025像素且浏览器宽度大于1025像素,则更改zoomWidthzoomHeight值。

我的IF声明在哪里出错?

<script>

if (screen.width >= 1025 && (document.documentElement.clientWidth >= 1025)) {
 $(document).ready(function() {

    $('.jqzoom').jqzoom({
    zoomWidth: 609,
    zoomHeight:756
    });

 });
}

// Start second IF statement

if (screen.width < 1024 && document.documentElement.clientWidth < 1024) {
$(document).ready(function() {
$('.jqzoom').jqzoom({
zoomWidth: 200,
zoomHeight:200
});

});
}
</script>

1 个答案:

答案 0 :(得分:3)

'if'语句仅在页面加载时执行一次。当您调整浏览器大小时,它们已经被执行并且不再执行。

使用jQuery的resize处理程序来检测resize:

 function checkWidth() {
    if (screen.width >= 1025 && (document.documentElement.clientWidth >= 1025)) {
        $(document).ready(function() {
            $('.jqzoom').jqzoom({
                zoomWidth: 609,
                zoomHeight: 756
            });

        });
    }

    // Start second IF statement
    if (screen.width < 1024 && document.documentElement.clientWidth < 1024) {
        $(document).ready(function() {
            $('.jqzoom').jqzoom({
                zoomWidth: 200,
                zoomHeight: 200
            });

        });
    }
}
$(document).ready(checkWidth);
$(document).resize(checkWidth);