JS網站廣告實現側邊欄滾動至div頂部后固定、鼠標滾動下拉側邊欄DIV固定


  網站或博客經常要掛廣告,固定在側邊欄上,每次用到場景都不一樣,每次都現找案例,今天把各個場景在這里匯總記錄一下!

  目前遇到這兩種固定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樣式不對,這個時候通常是樣式沖突或者繼承的是父類樣式,解決方案:重寫固定后的樣式!

      


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM