javascript - 当部分可见时将标题固定在顶部

标签 javascript jquery html

我试图创建一种效果,而不是当我的用户滚动时,我的 h1 粘在窗口的顶部。当父 div 滚动超过 h1 时,然后“释放”并再次正常滚动。当我的下一个 section 出现时,我想将下一个 h1 再次放在顶部,依此类推。

Fiddle

jQuery

$(document).ready(function(){
    $(window).scroll(function(){
        $('section h1').addClass('fixed');
    })
})

我也试过:

var section = $('section');
distance = section.offset().top,
$window = $(window);

$window.scroll(function() {
    if ( $window.scrollTop() >= distance ) {
       section.find('h1').addClass('fixed');
    }
});

最佳答案

您可以使用一点 jQuery 来做到这一点。

以下代码段计算每个部分到窗口顶部的偏移量。当一个部分到达窗口顶部时,它的标题是 <h1>位置改为position:fixed; .

DEMO

jQuery:

function fixTitle() {
    $('section.affix').each(function () {
        var $this = $(this);
        var offset = $this.offset().top-40;
        var scrollTop = $(window).scrollTop();

        if (scrollTop > offset) {
            $this.addClass('fixed');
        } else {
            $this.removeClass('fixed');
        }
    });
}

$(document).ready(function () {
    $(window).scroll(fixTitle);
});

CSS:

section {
    overflow:hidden;
    padding:0 20%;
    position:relative;
  text-align:justify;
}
section h1 {
    float:left;
    width:14%;
  padding-left:1.5%;
  line-height:40px;
    background:#fff;
    position:relative;
  z-index:1;
}
section .summary {
    float:right;
    width:70%;
}
.fixed h1:first-child {
    position:fixed;
    top:0;
}
h1:first-child:before{
  content:"";
  position:absolute;
  left:0;
  width:5%;
  height:100%;
  background-color:#4381B6;
  z-index:-1;


}
.fixed h1:first-child:before{
  width:100%;
  -webkit-transition:width 0.5s ease-in-out;
  transition: width 0.5s ease-in-out;
}

关于javascript - 当部分可见时将标题固定在顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22758599/

相关文章:

javascript - 如何过滤 jqGrid 数据而不是网格本身

javascript - 在页面之间移动时创建变量和 'storing it',jquery

javascript - 如何同时滚动两个div?

javascript - 使用 jquery 根据文本框的值隐藏或过滤 div

php - 我可以将 php 链接添加到 $query 吗?

javascript - 获取错误 403 : Access Not Configured. 请使用 Google Developers Console 为您的项目激活 API

javascript - HTML- 内容未在选项卡中正确显示

javascript - 如何根据 jQuery 中 bootstrap 下拉列表的选择显示和隐藏 div 元素

javascript - 拖放不起作用 : 'dropEffect' of undefined

html - 导航栏中的中心表单