如果只在视口宽度小于选中时运行jquery函数?

时间:2017-04-18 17:36:22

标签: jquery function if-statement

我想只在vieport宽度小于816像素时才运行jquery函数但是我无法让它工作。有人告诉我我做错了什么?

我主要使用Google Chrome开发工具模拟器,但它也出现在我的私人移动设备(Desire 820(1280x720屏幕))中。我曾试图使用window.width但没有成功。

<!-- language: lang-js -->
if ($('body').width() >= 816) 
{ 
    $(function()
    {
        $('.top-container').data('size','big');

        $(window).scroll(function()
        {
            if($(document).scrollTop() > 0)
            {
                if($('.top-container').data('size') == 'big')
                {
                    $('.top-container').data('size','small');
                    $('.top-container').stop().animate({height:'8vh'},600);
                    $('li').toggleClass('scroll');
                    $(".top-logo").toggleClass('scroll-logo');
                    $('.top-logo > a > img').toggleClass('scroll-logo');
                }
            }
            else
            {
                if($('.top-container').data('size') == 'small')
                {
                    $('.top-container').data('size','big');
                    $('.top-container').stop().animate({ height:'18vh' },600);
                    $('li').toggleClass('scroll').animate({},600);  
                    $(".top-logo").toggleClass('scroll-logo');
                    $('.top-logo > a > img').toggleClass('scroll-logo');

                }
            }
        });
    });
};

<!-- language: lang-html -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

1 个答案:

答案 0 :(得分:1)

这将为您解决问题:

$( window ).resize(function() {

  if ($('body').width()  >= 816) {  
    console.log('run my code!');
  };

  $( "body" ).prepend( "<div>" + $( window ).width() + "</div>" );
});

    $( window ).resize(function() {
    
      if ($('body').width()  >= 816) {  
      	console.log('run my code!');
      };
      
      $( "body" ).prepend( "<div>" + $( window ).width() + "</div>" );
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
&nbsp;
</div>

https://jsfiddle.net/p19qkb33/