提问者:小点点

在窗口调整大小后仅运行jquery函数以获得最小的视区宽度


我对块元素浮动动画的jquery脚本有一个问题。我想获得浮动框只有当窗口宽度大于1024px。

下面的代码工作得很好,但是当我打开桌面分辨率(大于1024)的页面并将大小调整为较小的宽度时,滚动可以激发相同的功能来改变css,就像在更大的分辨率上一样。

当窗口宽度小于1024px时,如何关闭/删除此css更改?

代码:

$(document).ready(function() {

    function stickyOfferBox() {
            var isMobile;
            if ($(window).width() > 1024) {
                isMobile = false; 

                var $sticky = $('.career-offer-box'),           
                    stickyOffset = $('.career-offer').offset().top - 80,
                    stickyOffsetRight = ($(window).width() - ($sticky.offset().left + $sticky.outerWidth())),
                    stickyWidth = $sticky.width(),
                    stickyHeight,               
                    stickyStopBreakpoint;


                if (!isMobile) {

                    $(window).scroll(function(){

                        var scroll = $(window).scrollTop();

                        if (scroll >= stickyOffset) {
                            $sticky.css({
                                'position': 'fixed',
                                'top': '80px',
                                'right': stickyOffsetRight,
                                'width': stickyWidth
                            });

                            stickyHeight = $sticky.height(); // We want only floating box height instead of static
                            stickyStopBreakpoint = $('#contact').offset().top - stickyHeight ;     

                        } else {
                            $sticky.css({
                                'position': 'relative',
                                'top': 'auto',
                                'right': 'auto',
                                'width': 'auto'
                            });
                        }

                        if (scroll >= (stickyStopBreakpoint - 160)) {
                            $sticky.css({
                                'position': 'absolute',
                                'top': stickyStopBreakpoint - 80,
                                'right': $sticky,
                                'width': stickyWidth
                            });
                        }
                    });
                }
            } else {
                isMobile = true;          
                return false;
            }
        }

    stickyOfferBox();  
    $(window).resize(stickyOfferBox);
});

共1个答案

匿名用户

如果我正确理解了您的代码,那么您只需从窗口中解除scroll事件的绑定。

$(window).unbind('scroll');

您应该创建如下结构:

if($(window).width() >= 1025){

  $(window).scroll(function(){ 

  /** your function code here **/

  });

}else{

$(window).unbind('scroll');

}