我有一个如下所示的博客页面。我想使用向上翻页或向下翻页按钮在博客文章之间切换。我为此目的创建了 javascript,但我不知道如何向上或向下切换侧边栏。
页面模板
|---------------------------------|
| header |
|---------------------------------|
|---------------------| |--------|
| blog 1 | | side |
| | | bar |
|---------------------| |--------|
|---------------------|
| blog 2 |
| |
|---------------------|
|---------------------|
| blog 3 |
| |
|---------------------|
每当我按向下翻页时,我应该在博客 2 周围使用页眉 + 侧边栏;之后,如果我再次按 向下翻页,我应该在博客 3 周围使用 header + sidebar。
插图,在下一页
|---------------------|
| 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
}
});
关于javascript - 如何在页面上向上或向下移动侧边栏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25874795/