根据窗口宽度更改 JavaScript

Change javascript according to window width

本文关键字:JavaScript 窗口      更新时间:2023-09-26

我认为这很简单,但经过 2 天的尝试,我仍然一无所知。基本上,如果屏幕宽度超过 767 像素,我需要运行一组命令,如果屏幕低于 767 像素,我需要运行另一组命令。

当屏幕宽度超过 767 像素时,我想:

<script type="text/javascript">
    var jsReady = false;//for flash/js communication
    // FLASH EMBED PART
    var flashvars = {};
    var params = {};
    params.quality = "high";
    params.scale = "noscale";
    params.salign = "tl";
    params.wmode = "transparent";
    params.bgcolor = "#111111";//change flash bg color here
    params.devicefont = "false";
    params.allowfullscreen = "true";
    params.allowscriptaccess = "always";
    var attributes = {};
    attributes.id = "flashPreview";
    swfobject.embedSWF("preview.swf", "flashPreview", "100%", "100%", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
    <!-- and much more code... -->
</script>

当屏幕窄于 768 像素时,我想运行:

<script type="text/javascript">  
        jQuery(function($){
            $.supersized({
                //Background image
                slides  :  [ { image : 'img/some_image.jpg' } ]                 
            });
        });
</script>

没错。。。对于台式机和平板电脑,我想显示全屏视频背景。对于较小的屏幕(小于 767 像素),我想显示单个静止图像背景。

您可以使用

$(window).width()获取窗口的当前大小,并在窗体的 resize 事件上附加处理程序。对于简单的使用,它就像

$(window).resize(funcion() {
    $width = $(window).width();
    if($width < 767) {
            $.supersized({
                //Background image
                slides  :  [ { image : 'img/some_image.jpg' } ]                 
            });
    } else {
        //if width is greater than 767
    }
});
if(screen.width > 767) {
   code A...
} else {
   code B...
}

由于您使用的是 JQuery,因此您可以使用以下内容:

if ($(window).width > 767) { ... }

这将返回窗口的当前大小,而不是最大值。