代码之家  ›  专栏  ›  技术社区  ›  Derek Adair

容器中的固定图像

css
  •  0
  • Derek Adair  · 技术社区  · 15 年前

    什么是使一个DIV沿着页面滚动的最好方法?

    使用了确切的效果@ http://store.apple.com/ (在产品添加到购物车后的结帐摘要上)

    编辑:或 this example -唉,它没有我想要的那么光滑=/

    3 回复  |  直到 15 年前
        1
  •  1
  •   rahul    15 年前

    在第二个示例中,他们使用jquery来实现这一点。捕获窗口对象的滚动事件,并使用 animate() 函数DIV的位置动态更改。

        2
  •  0
  •   Glo    15 年前
        3
  •  0
  •   Derek Adair    15 年前

    jquery节省了一天…再一次!

    CSS(中文):

    #wrapper {
      position: absolute;
      width: 200px;
    }
    
    #fancyDiv {
      position: absolute;
      top: 0;
    }
    
    #fancyDivt.fixed {
      position: fixed;
      top: 0;
    }
    

    HTML:

    <div id="commentWrapper">
      <div id="comment">
        <p>some text</p>
      </div>
    </div>
    

    jQuery:

    $(document).ready(function() {
        $(function () {
            var top = $('#fancyDiv').offset().top - parseFloat($('#fancyDiv').css('margin-top').replace(/auto/, 0));
            $(window).scroll(function (event) {
                  // what the y position of the scroll is
                  var y = $(this).scrollTop();
    
                  // whether that's below the div
                  if (y >= top) {
                    // if so, ad the fixed class
                    $('#fancyDiv').addClass('fixed');
                  } else {
                    // otherwise remove it
                    $('#fancyDiv').removeClass('fixed');
                  }
            });
        }
    });