浏览器滚动到它时修复div [英] Fix div when browser scrolls to it

查看:97
本文介绍了浏览器滚动到它时修复div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您向下滚动以下网址中的页面,'share'div将锁定到浏览器:

If you scroll down the page in the following URL, the 'share' div will lock onto the browser:

http://knowyourmeme.com/memes/pizza-is-a-vegetable

我假设他们正在应用的位置:fixed; 属性。如何用jQuery实现?

I'm assuming they are applying a position: fixed; attribute. How can this be achieved with jQuery?

推荐答案

您可以在下面找到一个示例。基本上你将一个函数附加到窗口滚动事件和跟踪 scrollTop 属性,如果它高于期望的阈值,则应用 position:fixed 和其他一些css属性。

You can find an example below. Basically you attach a function to window's scroll event and trace scrollTop property and if it's higher than desired threshold you apply position: fixed and some other css properties.

jQuery(function($) {
  function fixDiv() {
    var $cache = $('#getFixed');
    if ($(window).scrollTop() > 100)
      $cache.css({
        'position': 'fixed',
        'top': '10px'
      });
    else
      $cache.css({
        'position': 'relative',
        'top': 'auto'
      });
  }
  $(window).scroll(fixDiv);
  fixDiv();
});

body {
  height: 2000px;
  padding-top: 100px;
}
#getFixed {
  color: #c00;
  font: bold 15px arial;
  padding: 10px;
  margin: 10px;
  border: 1px solid #c00;
  width: 200px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="getFixed">This div is going to be fixed</div>

这篇关于浏览器滚动到它时修复div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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