2013-08-28 31 views
1

浮動DIV我jQuery的新手,我想股利在屏幕上方掛在頁面Scrolldown已超過50,我怎麼能做到這一點?如何實現對下滾

我想股利是永遠絕對的,不是固定不變的。

http://jsfiddle.net/8UCcY/

$(document).ready(function() { 
    $(window).scroll(function() { 
      if ($(window).scrollTop() > 50) { 
       $(".articlebutton").css("top", "0px"); //I want this value to change dynamically as the scrollbar moves down, so that the div stays on top of screen 
      } else { 
       $(".articlebutton").css("top", "-50px"); 
      } 
    }); 
}); 

回答

1

可以設置它位於頂部-100,因爲它是-50,滾動發生在50之後:

$(".articlebutton").css("top", ($(window).scrollTop()-100)+"px"); 
+0

謝謝。 :)很好的答案。 –

0

你可以做這樣的事情在該行:

$(".articlebutton").css("top", $(window).scrollTop()); 

或事件更好,使用position: fixed; top: 0;

0

爲什麼不能簡單地設置一個position:fixed;爲div?反正它總是處於頂端。見下面

.articlebutton div 
{ 
     position:fixed; 
     top:0; 
} 
+0

我不能。因爲初始位置是絕對的。寬度取決於屏幕的大小。 –

+0

寬度與您要設置的「頂部」屬性有什麼關係?爲什麼不將初始化位置固定而不是絕對?也許張貼的HTML? –

+0

由於div取自主窗口的位置,該窗口的大小調整爲屏幕的百分比。所以我不能使用固定的。 –

0

的CSS使div的財產

div{ 
position : fixed; 
top : 0px; 
} 

它會使你永遠DIV留在上面。無論你多麼滾動頁面

+0

謝謝,但在問題中我明確寫了沒有固定的div。 –

+0

.articlebutton/*查看文章的按鈕*/ { width:140px; height:50px; 背景:綠色; z-index:1000; left:180px; position:fixed; top:10px; } 反正你的CSS改變這一點,將工作 –

+0

和問題刪除的jQuery –

1

試試這個:

$(document).ready(function() { 
    $(window).scroll(function() { 
      if ($(window).scrollTop() <= 50) { 
       $(".articlebutton").css("top", $(window).scrollTop() - 50); //I want this value to change dynamically as the scrollbar moves down, so that the div stays on top of screen 
      } else { 
       $(".articlebutton").css("top", $(window).scrollTop() - 100); 
      } 
    }); 
}); 

Fiddle

+0

謝謝。但小提琴有一個錯誤。 –

+0

請解釋什麼錯誤是我會盡力解決.. ?? –

+0

@Abishek檢查你發佈的小提琴,你會看到。 –

1

DEMO

試試這個

$(document).ready(function() { 
    var top = $(".articlebutton").css('top'); 
    $(window).scroll(function() { 

     if ($(window).scrollTop() > 50) { 

      $(".articlebutton").animate({ 
       "top": $(window).scrollTop() + "px" 
      }, 400); 
     } else { 
      $(".articlebutton").animate({ 
       "top": top 
      }, 400); 
     } 

    }); 
}); 

希望這會有所幫助,謝謝

+0

我已編輯,現在它的工作原理檢查出 – SarathSprakash

+0

它不工作。對不起。感謝幫助。 –

+0

它的工作只是檢查它 – SarathSprakash