簡體   English   中英

使元素固定在滾動上

[英]Make element fixed on scroll

我試圖讓導航欄粘在頂部,當用戶向下滾動到導航欄,然后當用戶向上滾動超過導航欄時取消粘滯。 我知道這只能通過 JavaScript 實現。 我是 JavaScript 的初學者,所以越簡單越好。 JSFIDDLE 在這里。

HTML如下:

   <section class="main">
     <div id="wrap">
        <div id="featured">
     <div class="wrap">      
  <div class="textwidget">
    <div class="cup"><img src="#""></div>
<div id="header"></div></div></div></div></div></div></div>
<div class="whiteboard">
         <h1><a href="#">HELLO GUYS</a></h1> </div>
   </div>
          <div class="bg1">
            <h2> WE ARE AN EVENTS MANAGEMENT COMPANY BASED IN LONDON. </h2></div>

CSS如下:

      .main{text-align:center;}

      h1{
          -webkit-font-smoothing: antialiased;
              display:inline-block;
            font: 800 1.313em "proxima-nova",sans-serif; 
            padding: 10px 10px;
            margin: 20px 20px;
            letter-spacing: 8px;
            text-transform: uppercase;
              font-size:3.125em;
              text-align: center; 
              max-width: 606px;
      line-height: 1.45em;
      position: scroll;
          background-color:#e94f78;
          text-decoration: none;
          color:yellow;
          background-image:url;
      }

      h1 a{
        text-decoration: none;
        color:yellow;
                padding-left: 0.15em;
      }

      h2{
          -webkit-font-smoothing: antialiased;
              display:inline-block;
            font: 800 1.313em "proxima-nova",sans-serif; 
            letter-spacing: 8px;
            margin-top: 100px;
            text-transform: uppercase;
              font-size:3.125em;
              text-align: center; 
      line-height: 1.45em;
      position: scroll;
          text-decoration: none;
          color:white;
          z-index: -9999;
      }

      h2 a{
        text-decoration: none;
        color:white;
                padding-left: 0.15em;
      }

      h5{

      position: absolute;
              font-family:sans-serif; 
              font-weight:bold; 
              font-size:40px; 
              text-align: center; 
              float: right;
              background-color:#fff;
              margin-top: -80px;
              margin-left: 280px;
      }

      h5 a{

        text-decoration: none;
        color:red;
      }

      h5 a:hover{

        color:yellow;
      }

      #text1{
          -webkit-font-smoothing: antialiased;
              display:inline-block;
            font: 800 1.313em "proxima-nova",sans-serif; 
            margin: 20px 20px;
            letter-spacing: 8px;
            text-transform: uppercase;
              font-size:3.125em;
              text-align: center; 
              max-width: 606px;
      line-height: 1.45em;
      position: scroll;
          background-color:#E94F78;

      }

      #text1 a{
          color:yellow;
          text-decoration: none;
              padding-left: 0.15em;


      }

      #text1 a:hover{

          text-decoration: none;
          cursor:pointer;
      }

      .whiteboard{
          background-image:url(http://krystalrae.com/img/krystalrae-2012-fall-print-leopard-sketch.jpg);
          background-position: center;
          padding: ;
          background-color: #fff;
          z-index: 1000;
      }

      .bg{
        height:2000px;
        background-color:#ff0;
        background-image:url(http://alwayscreative.net/images/stars-last.jpg);
        position:relative;
        z-index: -9999;

      }
      .bg1{
        background-image:url(http://alwayscreative.net/images/stars-last.jpg);
        z-index: -9999;
        height:1000px;
      }
      /* Header */
      #wrap {
        margin: 0 auto;
        padding: 0;
        width: 100%;
      }

      #featured {
        background: #E94F78 url(http://www.creativityfluid.com/wp-content/themes/creativityfluid/images/img-bubbles-red.png) no-repeat top;
        background-size: 385px 465px;
        color: #fff;
        height: 535px;
        overflow: hidden;
        position: relative;
        z-index: -2;
      }


      #featured .wrap {
        overflow: hidden;
        clear: both;
        padding: 70px 0 30px;
        position: fixed;
        z-index: -1;
        width: 100%;
      }


      #featured .wrap .widget {
        width: 80%;
        max-width: 1040px;
        margin: 0 auto;
      }

      #featured h1,
      #featured h3,
      #featured p {
        color: yellow;
        text-shadow: none;
      }

      #featured h4{
        color:white;
        text-shadow:none;
      }

      #featured h4 {
        margin: 0 0 30px;
      }

      #featured h3 {
        font-family: 'proxima-nova-sc-osf', arial, serif;
        font-weight: 600;
        letter-spacing: 3px;
      }

      #featured h1 {
        margin: 0;
      }

      .textwidget{
        padding: 0;
      }

      .cup{
        margin-top:210px;
        z-index: 999999;
      }

      .container{font-size:14px; margin:0 auto; width:960px}
      .test_content{margin:10px 0;}
      .scroller_anchor{height:0px; margin:0; padding:0;background-image:url()}
      .scroller{background:#FFF;
        background-image:url(http://krystalrae.com/img/krystalrae-2012-fall-print-leopard-sketch.jpg);
       margin:0 0 10px; z-index:100; height:50px; font-size:18px; font-weight:bold; text-align:center; width:960px;}

你可以用一些簡單的 jQuery 來做到這一點:

http://jsfiddle.net/jpXjH/6/

var elementPosition = $('#navigation').offset();

$(window).scroll(function(){
        if($(window).scrollTop() > elementPosition.top){
              $('#navigation').css('position','fixed').css('top','0');
        } else {
            $('#navigation').css('position','static');
        }    
});

我不會打擾 jQuery 或 LESS。 在我看來,javascript 框架太過分了。

window.addEventListener('scroll', function (evt) {

  // This value is your scroll distance from the top
  var distance_from_top = document.body.scrollTop;

  // The user has scrolled to the tippy top of the page. Set appropriate style.
  if (distance_from_top === 0) {

  }

  // The user has scrolled down the page.
  if(distance_from_top > 0) {

  }

});

實現這個有一些問題,原始接受的答案沒有回答:

  1. 窗口的onscroll事件經常觸發。 這意味着您要么必須使用高性能的偵聽器,要么必須以某種方式延遲偵聽器。 jQuery Creator John Resig在此闡述如何實現延遲機制,以及您應該這樣做的原因。 在我看來,鑒於當今的瀏覽器和環境,高性能監聽器也可以。 這是 John Resig 建議的模式的實現
  2. position:fixed 在 css 中的工作方式,如果你向下滾動頁面並將一個元素從 position:static 移動到position: fixed ,頁面會“跳躍”一點,因為文檔“松動”了元素的高度。 您可以通過將高度添加到scrollTop並用另一個對象替換文檔正文中丟失的高度來擺脫它。 您還可以使用該對象來確定粘性項目是否已經移動到position: fixed並減少對代碼的調用恢復position: fixed到原始狀態:查看此處的小提琴
  3. 現在,處理程序在性能方面真正做的唯一昂貴的事情是在每次調用時調用scrollTop 由於間隔綁定處理程序也有其缺點,我將在這里論證您可以將事件偵聽器重新附加到原始滾動事件,使其感覺更快捷,而不必擔心。 但是,您必須在您定位/支持的每個瀏覽器上對其進行概要分析。 看到它在這里工作

這是代碼:

JS

/* Initialize sticky outside the event listener as a cached selector.
 * Also, initialize any needed variables outside the listener for 
 * performance reasons - no variable instantiation is happening inside the listener.
 */
var sticky = $('#sticky'),
    stickyClone,
    stickyTop = sticky.offset().top,
    scrollTop,
    scrolled = false,
    $window = $(window);

/* Bind the scroll Event */
$window.on('scroll', function (e) {
    scrollTop = $window.scrollTop();

    if (scrollTop >= stickyTop && !stickyClone) {
        /* Attach a clone to replace the "missing" body height */
        stickyClone = sticky.clone().prop('id', sticky.prop('id') + '-clone')
        stickyClone = stickyClone.insertBefore(sticky);
        sticky.addClass('fixed');
    } else if (scrollTop < stickyTop && stickyClone) {
        /* Since sticky is in the viewport again, we can remove the clone and the class */
        stickyClone.remove();
        stickyClone = null;
        sticky.removeClass('fixed');
    }
});

CSS

body {
    margin: 0
}
.sticky {
    padding: 1em;
    background: black;
    color: white;
    width: 100%
}
.sticky.fixed {
    position: fixed;
    top: 0;
    left: 0;
}
.content {
    padding: 1em
}

HTML

<div class="container">
  <div id="page-above" class="content">
    <h2>Some Content above sticky</h2>
    ...some long text...
  </div>
  <div id="sticky" class="sticky">This is sticky</div>
  <div id="page-content" class="content">
    <h2>Some Random Page Content</h2>...some really long text...
  </div>
</div>

給你,沒有框架,簡短而簡單:

var el = document.getElementById('elId');
var elTop = el.getBoundingClientRect().top - document.body.getBoundingClientRect().top;

window.addEventListener('scroll', function(){
    if (document.documentElement.scrollTop > elTop){
        el.style.position = 'fixed';
        el.style.top = '0px';
    }
    else
    {
        el.style.position = 'static';
        el.style.top = 'auto';
    }
});

您想使用jQuery WayPoints 這是一個非常簡單的插件,可以完全達到您所描述的效果。

最直接的實現

    $('.thing').waypoint(function(direction) {
  alert('Top of thing hit top of viewport.');
});

您需要設置一些自定義 CSS 以准確設置它卡住的位置,盡管對於大多數方法來說這是正常的。

此頁面將顯示您需要的所有示例和信息。

為了將來參考,它停止和啟動的一個例子是這個網站 這是一個“在野外”的例子。

你可以去 LESS CSS 網站http://lesscss.org/

他們的可停靠菜單很輕而且性能很好。 唯一需要注意的是,效果發生在滾動完成后。 只需做一個查看源代碼即可查看js。

你也可以用 css 來做到這一點。

只需使用position:fixed; 向下滾動時要修復的內容。

你可以在這里有一些例子:

http://davidwalsh.name/demo/css-fixed-position.php

http://demo.tutorialzine.com/2010/06/microtut-how-css-position-works/demo.html

window.addEventListener("scroll", function(evt) {
    var pos_top = document.body.scrollTop;   
    if(pos_top == 0){
       $('#divID').css('position','fixed');
    }

    else if(pos_top > 0){
       $('#divId').css('position','static');
    }
});

純 Javascript 解決方案(演示):

<br/><br/><br/><br/><br/><br/><br/>
<div>
  <div id="myyy_bar" style="background:red;"> Here is window </div>
</div>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>


<script type="text/javascript">
var myyElement = document.getElementById("myyy_bar"); 
var EnableConsoleLOGS = true;           //to check the results in Browser's Inspector(Console), whenever you are scrolling
// ==============================================



window.addEventListener('scroll', function (evt) {
    var Positionsss =  GetTopLeft ();  
    if (EnableConsoleLOGS) { console.log(Positionsss); }
    if (Positionsss.toppp  > 70)    { myyElement.style.position="relative"; myyElement.style.top = "0px";  myyElement.style.right = "auto"; }
    else                            { myyElement.style.position="fixed";    myyElement.style.top = "100px";         myyElement.style.right = "0px"; }
});



function GetOffset (object, offset) {
    if (!object) return;
    offset.x += object.offsetLeft;       offset.y += object.offsetTop;
    GetOffset (object.offsetParent, offset);
}
function GetScrolled (object, scrolled) {
    if (!object) return;
    scrolled.x += object.scrollLeft;    scrolled.y += object.scrollTop;
    if (object.tagName.toLowerCase () != "html") {          GetScrolled (object.parentNode, scrolled);        }
}

function GetTopLeft () {
    var offset = {x : 0, y : 0};        GetOffset (myyElement.parentNode, offset);
    var scrolled = {x : 0, y : 0};      GetScrolled (myyElement.parentNode.parentNode, scrolled);
    var posX = offset.x - scrolled.x;   var posY = offset.y - scrolled.y;
    return {lefttt: posX , toppp: posY };
}
// ==============================================
</script>

最近對我有用的解決方案是:

.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}

var header = document.getElementById("filters-tab");
var sticky = header.offsetTop;

if (window.pageYOffset > sticky) {
  header.classList.add("fixed");
} else {
  header.classList.remove("fixed");
}

當用戶向下滾動到導航欄時,我試圖使導航欄位於頂部,然后當用戶向上滾動越過導航欄時,導航欄不粘。 我了解這只能通過JavaScript來實現。 我是JavaScript的初學者,所以越輕松越好。 JSFIDDLE在這里。

HTML如下:

   <section class="main">
     <div id="wrap">
        <div id="featured">
     <div class="wrap">      
  <div class="textwidget">
    <div class="cup"><img src="#""></div>
<div id="header"></div></div></div></div></div></div></div>
<div class="whiteboard">
         <h1><a href="#">HELLO GUYS</a></h1> </div>
   </div>
          <div class="bg1">
            <h2> WE ARE AN EVENTS MANAGEMENT COMPANY BASED IN LONDON. </h2></div>

CSS如下:

      .main{text-align:center;}

      h1{
          -webkit-font-smoothing: antialiased;
              display:inline-block;
            font: 800 1.313em "proxima-nova",sans-serif; 
            padding: 10px 10px;
            margin: 20px 20px;
            letter-spacing: 8px;
            text-transform: uppercase;
              font-size:3.125em;
              text-align: center; 
              max-width: 606px;
      line-height: 1.45em;
      position: scroll;
          background-color:#e94f78;
          text-decoration: none;
          color:yellow;
          background-image:url;
      }

      h1 a{
        text-decoration: none;
        color:yellow;
                padding-left: 0.15em;
      }

      h2{
          -webkit-font-smoothing: antialiased;
              display:inline-block;
            font: 800 1.313em "proxima-nova",sans-serif; 
            letter-spacing: 8px;
            margin-top: 100px;
            text-transform: uppercase;
              font-size:3.125em;
              text-align: center; 
      line-height: 1.45em;
      position: scroll;
          text-decoration: none;
          color:white;
          z-index: -9999;
      }

      h2 a{
        text-decoration: none;
        color:white;
                padding-left: 0.15em;
      }

      h5{

      position: absolute;
              font-family:sans-serif; 
              font-weight:bold; 
              font-size:40px; 
              text-align: center; 
              float: right;
              background-color:#fff;
              margin-top: -80px;
              margin-left: 280px;
      }

      h5 a{

        text-decoration: none;
        color:red;
      }

      h5 a:hover{

        color:yellow;
      }

      #text1{
          -webkit-font-smoothing: antialiased;
              display:inline-block;
            font: 800 1.313em "proxima-nova",sans-serif; 
            margin: 20px 20px;
            letter-spacing: 8px;
            text-transform: uppercase;
              font-size:3.125em;
              text-align: center; 
              max-width: 606px;
      line-height: 1.45em;
      position: scroll;
          background-color:#E94F78;

      }

      #text1 a{
          color:yellow;
          text-decoration: none;
              padding-left: 0.15em;


      }

      #text1 a:hover{

          text-decoration: none;
          cursor:pointer;
      }

      .whiteboard{
          background-image:url(http://krystalrae.com/img/krystalrae-2012-fall-print-leopard-sketch.jpg);
          background-position: center;
          padding: ;
          background-color: #fff;
          z-index: 1000;
      }

      .bg{
        height:2000px;
        background-color:#ff0;
        background-image:url(http://alwayscreative.net/images/stars-last.jpg);
        position:relative;
        z-index: -9999;

      }
      .bg1{
        background-image:url(http://alwayscreative.net/images/stars-last.jpg);
        z-index: -9999;
        height:1000px;
      }
      /* Header */
      #wrap {
        margin: 0 auto;
        padding: 0;
        width: 100%;
      }

      #featured {
        background: #E94F78 url(http://www.creativityfluid.com/wp-content/themes/creativityfluid/images/img-bubbles-red.png) no-repeat top;
        background-size: 385px 465px;
        color: #fff;
        height: 535px;
        overflow: hidden;
        position: relative;
        z-index: -2;
      }


      #featured .wrap {
        overflow: hidden;
        clear: both;
        padding: 70px 0 30px;
        position: fixed;
        z-index: -1;
        width: 100%;
      }


      #featured .wrap .widget {
        width: 80%;
        max-width: 1040px;
        margin: 0 auto;
      }

      #featured h1,
      #featured h3,
      #featured p {
        color: yellow;
        text-shadow: none;
      }

      #featured h4{
        color:white;
        text-shadow:none;
      }

      #featured h4 {
        margin: 0 0 30px;
      }

      #featured h3 {
        font-family: 'proxima-nova-sc-osf', arial, serif;
        font-weight: 600;
        letter-spacing: 3px;
      }

      #featured h1 {
        margin: 0;
      }

      .textwidget{
        padding: 0;
      }

      .cup{
        margin-top:210px;
        z-index: 999999;
      }

      .container{font-size:14px; margin:0 auto; width:960px}
      .test_content{margin:10px 0;}
      .scroller_anchor{height:0px; margin:0; padding:0;background-image:url()}
      .scroller{background:#FFF;
        background-image:url(http://krystalrae.com/img/krystalrae-2012-fall-print-leopard-sketch.jpg);
       margin:0 0 10px; z-index:100; height:50px; font-size:18px; font-weight:bold; text-align:center; width:960px;}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM