使用Javascript在Scroll Position的基础上交换CSS类 [英] Swap CSS class on the basis of Scroll Position with Javascript

查看:88
本文介绍了使用Javascript在Scroll Position的基础上交换CSS类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找重新创建Apple Store购物车边栏。

I'm looking to re-create the Apple Store shopping cart sidebar.

http ://store.apple.com/us/configure/MB535LL/A?mco = MTA4MTg3NTQ

类似于position:fixed,除了它以CSS类pinned_top开头为position:absolute,然后在达到某个scroll-y位置时切换到CSS类浮动。

It is similar to "position: fixed" except that it starts out as "position: absolute" with the CSS class "pinned_top" and then switches to CSS class "floating" when a certain scroll-y position is reached.

我一直在寻找它,看起来教程应该很明显,但我还没有找到任何东西。有什么帮助?

I've looked EVERYWHERE for this, it seems a tutorial should be obvious but I'm yet to find anything. Any help?

推荐答案

你必须处理 window.onscroll 事件,并检查元素位置,如果 scrollTop 大于元素的位置,你将元素固定在顶部,如果没有,你将元素放在最初的位置。

You will have to handle the window.onscroll event, and check the element position, if the scrollTop is greater than the position of your element, you set the element fixed at top, if not, you place the element where it originally was.

使用jQuery的示例

$(function () { 
  var $el = $('.fixedElement'), 
      originalTop = $el.offset().top;  // store original top position

  $(window).scroll(function(e){ 
    if ($(this).scrollTop() > originalTop ){ 
      $el.css({'position': 'fixed', 'top': '0px'}); 
    } else { 
      $el.css({'position': 'absolute', 'top': originalTop}); 
    } 
  }); 
});

这篇关于使用Javascript在Scroll Position的基础上交换CSS类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆