Подтвердить что ты не робот

Изменить стиль элемента на странице прокрутки

Я хочу изменить видимость элемента после прокрутки пользователя вниз на 100 пикселей.

У меня уже есть код,

var fixed = false;
$(document).scroll(function() {
    if( $(this).scrollTop() >= 100 ) {
        if( !fixed ) {
            fixed = true;
            $('#logo-scroll').css({position:'fixed', display:'visible !important'});
        }
    } else {
        if( fixed ) {
            fixed = false;
            $('#logo-scroll').css({display:'none'});
        }
    }
});​

JSFiddle.

Код имеет две проблемы.

  • Он не является невидимым по умолчанию, я хочу, чтобы он стал невидимым.

  • Он не повторяется, когда пользователь прокручивает резервную копию, он не становится невидимым.

Подробнее,

Я хочу сделать что-то вроде этого заголовка, но, как вы видите, есть определенный момент, когда вы видите половину маленького логотипа и ЧАСТЬ тем больше. Это не влияет на techcrunch, так как заголовок небольшой, но на моем сайте он делает это. Я сделал все, мне просто нужно запустить его в display:none и стать видимым после 100px.

4b9b3361

Ответ 1

Использование: display:block; и display:none;

jsFiddle DEMO

Добавьте это в свой CSS:

#logo-scroll{ display:none; position:fixed; }

JQ:

var $logo = $('#logo-scroll');
$(document).scroll(function() {
    $logo.css({display: $(this).scrollTop()>100 ? "block":"none"});
});

Кстати: на странице TC это просто игра CSS с z-индексами. больше ничего. все элементы видны при загрузке страницы, это просто прокрутка, которая создает нижний элемент z-index под большим логотипом.

В plain Javascript будет выглядеть как this:

var win = window,
    docEl = document.documentElement,
    $logo = document.getElementById('logo-scroll');

win.onscroll = function(){
   var sTop = (this.pageYOffset || docEl.scrollTop)  - (docEl.clientTop || 0);
   $logo.style.display =  sTop > 100 ? "block":"none" ;
};

Ответ 2

Хорошо, на этот вопрос уже был дан ответ. просто добавив лучший пример, который может быть полезен для других, и это именно то, что нужно оператору.

код и демонстрация

Отредактировано: добавлен фактический код из исходного источника.

JQuery

// This function will be executed when the user scrolls the page.
$(window).scroll(function(e) {
    // Get the position of the location where the scroller starts.
    var scroller_anchor = $(".scroller_anchor").offset().top;

    // Check if the user has scrolled and the current position is after the scroller start location and if its not already fixed at the top 
    if ($(this).scrollTop() >= scroller_anchor && $('.scroller').css('position') != 'fixed') 
    {    // Change the CSS of the scroller to hilight it and fix it at the top of the screen.
        $('.scroller').css({
            'background': '#CCC',
            'border': '1px solid #000',
            'position': 'fixed',
            'top': '0px'
        });
        // Changing the height of the scroller anchor to that of scroller so that there is no change in the overall height of the page.
        $('.scroller_anchor').css('height', '50px');
    } 
    else if ($(this).scrollTop() < scroller_anchor && $('.scroller').css('position') != 'relative') 
    {    // If the user has scrolled back to the location above the scroller anchor place it back into the content.

        // Change the height of the scroller anchor to 0 and now we will be adding the scroller back to the content.
        $('.scroller_anchor').css('height', '0px');

        // Change the CSS and put it back to its original position.
        $('.scroller').css({
            'background': '#FFF',
            'border': '1px solid #CCC',
            'position': 'relative'
        });
    }
});

HTML

<div class="container">
    <div class="test_content">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus interdum metus nec neque convallis id interdum nibh aliquet. Nulla eget varius diam. Ut ut dolor dolor. Mauris vehicula sodales mi quis euismod. In sem metus, volutpat nec fringilla sed, fermentum ac turpis. Cras aliquam venenatis rutrum. Donec pharetra ante sit amet justo pellentesque nec consequat ante elementum. Ut imperdiet iaculis tortor, id pretium urna pharetra sit amet. Aenean pharetra nunc risus, ac scelerisque urna. Morbi dictum egestas augue, in euismod metus commodo ac. Duis nisl ante, consequat et tincidunt id, eleifend eu ante. Integer lectus velit, tempus eu feugiat et, adipiscing ut mauris.
    </div>

    <!-- This div is used to indicate the original position of the scrollable fixed div. -->
    <div class="scroller_anchor"></div>

    <!-- This div will be displayed as fixed bar at the top of the page, when user scrolls -->
    <div class="scroller">This is the scrollable bar</div>

    <div class="test_content">
        Quisque sollicitudin elit vitae diam consequat accumsan. Suspendisse potenti. Donec dapibus tortor at justo eleifend at pellentesque leo lobortis. Etiam ultrices leo et nulla iaculis eu facilisis augue fermentum. Pellentesque eu leo purus. Vestibulum bibendum, metus at bibendum blandit, lacus neque porttitor diam, id facilisis lectus mauris et leo. Donec adipiscing interdum lacus sed condimentum. In auctor sollicitudin orci, ac interdum risus aliquet ullamcorper. Curabitur mollis accumsan vulputate. Etiam adipiscing diam nec dui posuere ut tincidunt felis tristique. Vestibulum neque enim, placerat sed placerat commodo, consectetur ac mauris. Sed ultrices pretium nibh, a blandit libero imperdiet pulvinar. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;
    </div>
    ...
</div>

CSS

.container{font-size:14px; margin:0 auto; width:960px}
.test_content{margin:10px 0;}
.scroller_anchor{height:0px; margin:0; padding:0;}
.scroller{background:#FFF; border:1px solid #CCC; margin:0 0 10px; z-index:100; height:50px; font-size:18px; font-weight:bold; text-align:center; width:960px;}