增强功能并在窗口大小低于 770 像素时将其关闭

Enhance a function and turn it off when window size is below 770px

本文关键字:像素 功能 窗口大小 增强      更新时间:2023-09-26

在我的项目页面上有两个网格,一个用于图像,一个用于包含有关项目信息的框,信息框的位置是固定的,因此它与页面一起滚动 - 使用下面的JavaScript,我设法让它在到达页脚时停止滚动。看看这里: http://meeped.co.uk:93/portfolio/ambition-world.html1

我遇到的问题是,在像iPhone这样的非常小的屏幕上,我想禁用滚动,并为每个网格(图像网格,信息框)提供100%。但是我似乎不知道如何阻止该功能在屏幕尺寸超过 770 时触发并重新打开它。我几乎做到了,但是由于在该功能上它增加了边距,因此当它在小屏幕上禁用时,边距将保留,从而产生一个我无法摆脱的大空白空间。 有什么想法吗?

//StickyBox
$(function () {
    $.fn.scrollBottom = function () {
        return $(document).height() - this.scrollTop() - this.height();
    };
    var $StickyBox = $('.detailsBox');
    var $window = $(window);
    $window.bind("scroll resize", function () {
        var gap = $window.height() - $StickyBox.height() - 10;
        var visibleFoot = 255 - $window.scrollBottom();
        var scrollTop = $window.scrollTop();
        if (scrollTop < 50) {
            $StickyBox.css({
                top: (130 - scrollTop) + "px",
                bottom: "auto"
            });
        } else if (visibleFoot > gap - 100) {
            $StickyBox.css({
                top: "auto",
                bottom: visibleFoot + "px"
            });
        } else {
            $StickyBox.css({
                top: 80,
                bottom: "auto"
            });
        }
    });
});

尝试添加:

if($window.width() <= 770) { 
    // reset your sticky box's margins
    $StickyBox.css({
      top: 'auto',
      bottom: 'auto'
    });
    return;
}

在事件侦听器中声明的 var 之后,例如:

$window.bind("scroll resize", function () {
    var gap = $window.height() - $StickyBox.height() - 10;
    var visibleFoot = 255 - $window.scrollBottom();
    var scrollTop = $window.scrollTop();
    if($window.width() <= 770) { 
        // reset your sticky box's margins
        $StickyBox.css({
          top: 'auto',
          bottom: 'auto'
        });
        return;
    }
    if (scrollTop < 50) {
        $StickyBox.css({
            top: (130 - scrollTop) + "px",
            bottom: "auto"
        });
    } else if (visibleFoot > gap - 100) {
        $StickyBox.css({
            top: "auto",
            bottom: visibleFoot + "px"
        });
    } else {
        $StickyBox.css({
            top: 80,
            bottom: "auto"
        });
    }

$window.bind("scroll resize"回调中声明所有变量后立即添加此项。

你可以

这样做:

$window.bind("scroll resize", function () {
   if($(this).width() < 770) {
       return;
   }
   // rest of your code...
$(window).resize(function(){
   if($(window).width() > 770) {
      // if it is more than 770
   } else {
      // if it is less or equal
   }
})

这个怎么样?

function onlyIfWidthGreaterThan(width, fn) {
    if ($(window).width() > width) {
        fn();
    }
}

用法如下:

onlyIfWidthGreaterThan(770, function() {
    // do your stuff
});