如何用屏幕宽度启动js功能

时间:2015-01-01 22:09:04

标签: javascript jquery

我有一个左侧菜单,我可以通过单击按钮滑出,但我想在屏幕宽度低于一定大小时自动隐藏它,因此按钮单击会将其恢复。我做错了什么?

$(function () {

if (screen.width > 1200) {

    $(".ncLeftMenuButton").click(function () {
        $(".ncLeftMenuClosed").switchClass("ncLeftMenuClosed", "ncLeftMenu", 1000);
        $(".ncLeftMenu").switchClass("ncLeftMenu", "ncLeftMenuClosed", 1000);
        $(".ncMainBlockClosed").switchClass("ncMainBlockClosed", "ncMainBlock", 1000);
        $(".ncMainBlock").switchClass("ncMainBlock", "ncMainBlockClosed", 1000);
    });
}

else {
    $(".ncLeftMenuButton").load(function () {
        $(".ncLeftMenu").switchClass("ncLeftMenu", "ncLeftMenuClosed", 1000);
        $(".ncLeftMenuClosed").switchClass("ncLeftMenuClosed", "ncLeftMenu", 1000);
        $(".ncMainBlock").switchClass("ncMainBlock", "ncMainBlockClosed", 1000);
        $(".ncMainBlockClosed").switchClass("ncMainBlockClosed", "ncMainBlock", 1000);
    });
}

});

2 个答案:

答案 0 :(得分:0)

screen.width将获得用户屏幕分辨率的大小。我想你想要获得浏览器窗口的大小。由于你使用的是jQuery,你可以使用$(window).height()甚至$(document).height();

if ($(window).height() > 1200) {

如果您想在调整浏览器大小时触发该功能,最好有一个resize事件:

$( window ).resize(function() {
  if ($(window).height() > 1200) {
     // Your code
  }
});

PS:你也可以只使用css @media queries来做你想做的事。

<style>
  @media (max-width: 1200px) {
    do some css things
  }
</style>

答案 1 :(得分:0)

我能够解决自己的问题。感谢任何帮助过的人。

$(document).ready(function () {
var $window = $(window);

// Function to handle changes to style classes based on window width
function checkWidth() {
    if ($window.width() < 1300) {
        $('.ncLeftMenu').removeClass('ncLeftMenu').addClass('ncLeftMenuClosed');
        $('.ncMainBlock').removeClass('ncMainBlock').addClass('ncMainBlockClosed');

                $(".ncLeftMenuButton").click(function () {
                    $(".ncLeftMenu").switchClass("ncLeftMenu", "ncLeftMenuClosed", 1000);
                    $(".ncLeftMenuClosed").switchClass("ncLeftMenuClosed", "ncLeftMenu", 1000);
                    $(".ncMainBlockClosed").switchClass("ncMainBlockClosed", "ncMainBlock", 1000);
                    $(".ncMainBlock").switchClass("ncMainBlock", "ncMainBlockClosed", 1000);

                });
    };

    if ($window.width() >= 1300) {
        $('.ncLeftMenuClosed').removeClass('ncLeftMenuClosed').addClass('ncLeftMenu');
        $('.ncMainBlockClosed').removeClass('ncMainBlockClosed').addClass('ncMainBlock');
    }
}

// Execute on load
checkWidth();

// Bind event listener
$(window).resize(checkWidth);

});