![](/img/trans.png)
[英]How to make a static sidebar, which doesn't move when page is scrolled down
[英]How to move sidebar on page up or down pressed?
我有一個如下所示的博客頁面。 我想使用向上翻頁或向下翻頁按鈕在博客文章之間切換。 我已經為此目的創建了javascript,但我不知道如何向上或向下切換側邊欄。
頁面模板
|---------------------------------|
| header |
|---------------------------------|
|---------------------| |--------|
| blog 1 | | side |
| | | bar |
|---------------------| |--------|
|---------------------|
| blog 2 |
| |
|---------------------|
|---------------------|
| blog 3 |
| |
|---------------------|
每當我按下page down時 ,都應該在Blog 2周圍加上標題和側邊欄 ; 之后,如果我再按一次向下翻頁 ,則應該在博客3周圍加上標題和側邊欄 。
插圖,下一頁
|---------------------|
| blog 1 |
| |
|---------------------|
|---------------------------------|
| header |
| |
|---------------------------------|
|---------------------| |--------|
| blog 2 | | side |
| | | bar |
|---------------------| |--------|
|---------------------|
| blog 3 |
| |
|---------------------|
我的Javascript代碼;
var documentOrder = 0;
function prepareEventHandlers(){
var blogs = document.getElementsByClassName("blogBox");
// What should I write to move sidebar and header?
documentOrder = documentOrder + 1 ;
}
window.onload = function () {
prepareEventHandlers();
}
我的網頁正文;
<body>
<span id="top"></span>
<div id="wrapper" class="auto-style2" style="width: 1340px">
<div class="blankHeader h120 w1180"></div>
<div id="sidebar">
</div>
<div id="allBlogPosts">
<div id="blog1" class="blogBox">
</div>
<div id="blog2" class="blogBox">
</div>
<div id="blog3" class="blogBox">
</div>
</div>
</div>
</body>
這不是一個完整的解決方案,它只是您進行工作的指針
放置它,以便您獲得一些指示。
您可以使用Jquery插件獲取粘性標題和側邊欄,也可以嘗試根據需要構建自己的自定義功能。 我在需要粘性側邊欄的項目中使用了這種方法,並且效果很好。
第1步:將頁眉和側欄都設置為position:absolute,您將需要一個父包裝容器來容納頁面上的所有內容,該包裝器應為position:relative
.wrapperContainer{
position:relative
}
.header{
position:absolute;
top:0; /*Default top can get changed as per your case*/
left:0;
}
.sidebar{
position:absolute;
top:100px;/*Default top can get changed as per your case*/
right:0;
}
第2步:在您的JS中向窗口滾動事件添加處理程序,並在頁面滾動時更改頁眉和側欄的頂部位置。 使用window.pageYOffset屬性可獲取從垂直零值開始的垂直滾動窗口的數量。
var windowScrolled = 0,
verticalHeaderOffset = 0,
verticalSidebarOffset = 0,
// These offsets will depend on you requirements, they can be any +ve/-ve number as per your case
$(window).on("scroll", function(){
windowScrolled = window.pageYOffset;
if(windowScrolled > 0){
$( ".header" ).animate({top: (windowScrolled + verticalHeaderOffset )}, 1000, function() {
// Animation complete, you can remove this whole function handler if not needed
});
$( ".sidebar" ).animate({top: (windowScrolled + verticalSidebarOffset )}, 1000, function() {
// Animation complete, you can remove this whole function handler if not needed
});
}
else{
$( ".header" ).animate({top: 0}, 1000); // Reset to initial value
$( ".sidebar" ).animate({top: 100)}, 1000); // Reset to initial value
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.