滚动bugg时垂直固定位置

时间:2014-12-08 19:43:22

标签: jquery html css sass

我正在尝试在我的网站上制作一些东西,但它不会像我想到的那样工作。 我的网站上有一个带有position: absolute属性的div。当我向下滚动时,它必须沿着页面滚动,但是当它从我的屏幕的顶部看起来像20px时,元素必须被修复。
问题是它可以工作,但是当元素必须是fixed时,它就会出错并且没有做我想做的事。

我很清楚我的想法,如果没有,请在评论中提出,我会尽力澄清。

为了让一切更加清晰,以下是错误的生活预览:http://www.eranmachiels.nl

我使用的代码:

[HTML]

<div class="personalInfo">
    <div class="photo">
        <img src="assets/web-gallery/me.jpg" />
    </div>
    <span class="me">Eran Machiels</span>
    <span class="somethingMore">An 18 years old webdeveloper</span>
</div>

[SASS]

.personalInfo {
    position: absolute; 
    margin: 0 auto;
    color: #fff;
    @include text-shadow(1px 1px #000);
    text-align: center;
    font-size: 15px;
    z-index: 2;
    width: 212px;

    .photo {
         border: solid 6px #fff;
        overflow: hidden;
        height: 150px;
        width: 150px;
        margin: auto;
        @include border-radius(50%);

        img {
            width: 150px;
            height: 150px;
            margin-left: -2px;
            @include border-radius(50%);
        }
    }   

    .me {
        font-size: 20px;
        font-weight: bold;
        display: block;
    }
}

[jQuery的]

if($(window).scrollTop() + 20 > $('.personalInfo').offset().top) {
    $('.personalInfo').css({
        'position': 'fixed',
        'top': 20
    }).find('.me, .somethingMore').stop().fadeOut(100);


} else {
    $('.personalInfo').css({
        'position': 'fixed',
        'top': $(window).height() / 2 - $('.personalInfo').height() / 2 + 'px'
    }).find('.me, .somethingMore').stop().fadeIn(100);
}

+20top: 20是因为我希望元素在到达页面顶部之前剩下20个像素时停止。
也许这是非常愚蠢的事情,但我无法得到解决方案 提前谢谢!

1 个答案:

答案 0 :(得分:0)

不要弄乱你的CSS和jquery。简单。

<强> CSS:

.notScrolling{
   position: relative
   margin: 0 auto;
   top: 100px;
}
.whenScrolling {
    position: fixed;
    top: 20px;
    left: 0;
    right:0;
}

<强> Jquery的:

$(document).ready(function(){
function scroll() {
    if ($(window).scrollTop() >= someValue) {
        $('.className').removeClass('notScrolling').addClass('whenScrolling');
    } else {
        $('.className').removeClass('whenScrolling').addClass('notScrolling');
    }
}
document.onscroll = scroll;
});

希望这有帮助。

相关问题