网站或博客经常要挂广告,固定在侧边栏上,每次用到场景都不一样,每次都现找案例,今天把各个场景在这里汇总记录一下!

  目前遇到这两种固定div的场景:1、侧边栏滚动至div顶部后固定 ;2、滚动下拉侧边栏DIV固定

  场景一、JS 实现DIV 滚动至顶部后固定

       代码如下:

<!DOCTYPE HTML>
<html>
<head>
  <meta charset="UTF-8">
  <title>DIV滚动至顶部后固定</title>
</head>
<body style="height:2000px;">
<div style="height: 200px"></div>
<div id="nav_keleyi_com" style="position:relative;top:0;background:#00f;width:100px; height:100px">
  Test Div
</div>
<script type="text/javascript">
  function menuFixed(id) {
    var obj = document.getElementById(id);
    var _getHeight = obj.offsetTop;

    window.onscroll = function () {
      changePos(id, _getHeight);
    }
  }

  function changePos(id, height) {
    var obj = document.getElementById(id);
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    if (scrollTop < height) {
      obj.style.position = 'relative';
    } else {
      obj.style.position = 'fixed';
    }
  }
  window.onload = function () {
    menuFixed('nav_keleyi_com');
  }
</script>
</body>

  场景二、鼠标滚动下拉侧边栏DIV固定

    一般博客侧边栏高度小于主体内容区时,滚动条滚动到到侧边栏底部时,侧边栏固定。

$.fn.scrollFix = function (opt) {
    var defaults = {
        baseTop: 50, // 初始top值
        main: ".main"  // 主体区选择器
    };
    var settings = $.extend(defaults, opt);
    var $window = $(window),
        $this = $(this),
        windowHeight,
        scrollTop,
        thisHeight,
        $main = $(settings.main),
        mainHeight;
    $window.scroll(function () {
        windowHeight = $window.height();
        scrollTop = $window.scrollTop();
        mainHeight = $main.height();
        $this.each(function (idx, val) {
            thisHeight = $(this).height();
            // 当主体区高度小于侧边栏时不做处理
            if (mainHeight < thisHeight) {
                return false;
            }
            // 当主体区高度大于侧边栏,且下滚高度+窗口高度大于侧边栏高度时,固定侧边栏
            if (scrollTop + windowHeight > thisHeight) {
                $(this).css({
                    position: 'fixed',
                    bottom: "50px"
                    // top: (thisHeight - windowHeight) > 0 ? -(thisHeight - windowHeight) - 30 : settings.baseTop
                    //  left: (idx*100) +"px"
                    // 如果当前元素的高度大于窗口高度,则上移 当前元素高度与窗口高度的差值,
                    // 否则紧贴窗口顶部
                });
            } else {
                $(this).css({
                    position: 'static'
                });
            }
        });
    });

}

 注意:

         1、页面不生效,解决办法:首先看看文件路径、然后看是否是延迟加载、最后打开控制台看看是否有语法错误

         2、js生效了,div消失了,这种情况我遇到了,打开控制台发现div 的 top:8090 ,所以页面上看不到,固定后修改样式添加:obj.style.top= '10px';

         3、固定后css样式不对,这个时候通常是样式冲突或者继承的是父类样式,解决方案:重写固定后的样式!

      

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/aitree/p/14314041.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!