【问题标题】:Setting CSS value limits of the window scrolling animation设置窗口滚动动画的 CSS 值限制
【发布时间】:2012-08-11 21:02:10
【问题描述】:

我有一个随着用户向下滚动而滑动的

地图。然而,它似乎让地图永远滚动,永远不会让用户真正到达页面底部(有一个页脚)。

我要做的是让

在到达另一个动态大小(高度可变)
的末尾时停止滚动。这两个
并排并在同一行中。

这是我用来使正确的 div 随用户滚动而移动的 JavaScript 代码:

$(function() {

    var $sidebar   = $("#map"),
        $window    = $(window),
        offset     = $sidebar.offset(),
        topPadding = 15;

    $window.scroll(function() {
        if ($window.scrollTop() > offset.top) {
            $sidebar.stop().animate({
                marginTop: $window.scrollTop() - offset.top + topPadding
            });
        }
        else {
            $sidebar.stop().animate({
                marginTop: 0
            });
        }
    });
});

【问题讨论】:

  • 它正在使用 Twitter Bootstrap。右侧有一个 ID 为“地图”的 Google 地图。

标签: javascript jquery html css sticky


【解决方案1】:

你不能将animate() 方法与滚动功能一起使用,它会产生冲突,因为滚动值会一直变化,jQuery 不能无限重复相同的动画。停止也不会解决这个问题,或者我无法做到。

我在if 语句中suggest to use variation

Here is not working animate sample with animate usage.

Here is same example working with css method.

$(window).scroll(function() {
    var scrollVal = $(this).scrollTop();
    if ( scrollVal > offset.top) {
        $sidebar.css({
           'margin-top': (($window.scrollTop() - offset.top) + topPadding) + 'px'
                       //added +'px' here to prevent old internet explorer bugs
        });
    } else {
        $sidebar.css({'margin-top':'0px'});
    }
});

注意:如果你想用else if扩展你的if语句,不要使用else,它也会产生冲突。相信我,我对这个问题非常有经验。

更新:

您也可以更改计算限制的方法。我想你想修复导航,你的 html 是这样的:

<div class="wrapper">
    <div class="header">header</div>
    <span id="subnav">hold this</span>
</div>​

和 jQuery 计算应该是这样的: Here is working jsFiddle.

$(document).ready(function() {
   $(window).scroll(function() {
       var headerH = $('.header').outerHeight(true);
      //this will calculate header's full height, with borders, margins, paddings
       console.log(headerH);
       var scrollVal = $(this).scrollTop();
        if ( scrollVal > headerH ) {
        //when scroll value reach to your selector
            $('#subnav').css({'position':'fixed','top' :'0px'});
        } else {
            $('#subnav').css({'position':'static','top':'0px'});
        }
    });
 });​

【讨论】:

  • 现在它什么都不做。我觉得这是因为存在变量问题。想法?
  • 你的计算也有问题,我更新了答案。
猜你喜欢
  • 1970-01-01
  • 2013-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
  • 1970-01-01
  • 1970-01-01
  • 2013-04-21
相关资源
最近更新 更多