在滚动上创建粘性标题,固定位置会中断标题

时间:2017-07-14 07:15:41

标签: javascript jquery html css position

我在滚动时制作了一个粘性标题,所以当标题栏到达页面顶部时,它会粘在那里。我遇到的问题是固定位置,使其粘在页面顶部。

当我需要固定到标题的位置时,当它需要变成粘性时,它会从包装器中溢出,我希望它保持当前形式并且只是坚持到顶部,我已经玩了很多不同的方法来编码这个并没有找到解决方案。

滚动此页面时,请查看我的意思:http://cameras.specced.co.uk/compare/297/Fujifilm_FinePix_XP80 (带有RED边框的div是我想要坚持到顶部的那个)

HTML:

<!-- FIXED HEADER -->
<div class="container">
    <div class="row">
        <div class="compare1_fixed">
            <div class="compare1_fixed_score">
            </div>
            <div class="compare1_fixed_name">
                <?php echo $brand['brand'] . " " . $model['model'] . " " . "Specifications"; ?>
            </div>
            <div class="compare1_fixed_social">
                <div class="compare1_fixed_social_icon">
                    <a href="http://google.com">
                        <img src="http://specced.co.uk/images/ui/facebook.png">
                    </a>
                    <a href="http://google.com">
                        <img src="http://specced.co.uk/images/ui/twitter.png">
                    </a>
                    <a href="http://google.com">
                        <img src="http://specced.co.uk/images/ui/google.png">
                    </a>
                    <a href="http://google.com">
                        <img src="http://specced.co.uk/images/ui/email.png">
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

CSS:

.compare1_fixed {
    width:100%;
    height:50px;
    clear: both;
    border:1px solid red;
}

. compare1_fixed_fixed {
    position:fixed;
}

.compare1_fixed_score {
    width:200px;
    height:50px;
    float: left;
    background-color:#222222;
}

.compare1_fixed_social {
    width:200px;
    height:50px;
    float:right;
}

.compare1_fixed_social_icon {
    display: inline-block;
}

.compare1_fixed_social_icon img {
    max-height: 50px;
    max-width: 50px;
    float: left;
}
.compare1_fixed_social_icon img:hover {
    opacity:.7;
}


.compare1_fixed_name {
    width:calc(100% - 400px);
    height:50px;
    display: inline-block;
    line-height: 50px;
    font-size:18px;
    font-weight: 600;
    padding-left:10px;
}

JS:

/* STICKY HEADER */
$(document).ready(function() {

  $(window).scroll(function () {

      console.log($(window).scrollTop())
    if ($(window).scrollTop() > 200) {
      $('.compare1_fixed').addClass('compare1_fixed_fixed');
    }
    if ($(window).scrollTop() < 201) {
      $('.compare1_fixed_fixed').removeClass('compare1_fixed_fixed');
    }
  });
});

1 个答案:

答案 0 :(得分:0)

固定位置会使元素占据整页宽度,

相应地修改您的CSS

  .compare1_fixed_fixed {
        position: fixed;
        top: 50px;
        width: 87%;
        z-index: 5;
        background-color: #fff;
    }

希望这会有所帮助..