Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

javascript - Change Element Style On Page Scroll

I want to change the visibility of an element after the user scrolls down 100px.

I have some code already,

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.

The code has two problems.

  1. It doesn't default to be invisible, I want it so it starts invisible.

  2. It doesn't repeat, when the user scrolls back up, it doesn't go back being invisible.

More details,

I want to make something like this header, but, as you can see, there's a certain point where you see half of the small logo, and a PART of the bigger one. It doesn't affect techcrunch much as the header is small, but on my site, it does. I have made everything, I just need to start it in display:none, and become visible after 100px.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use: display:block; and display:none;

jsFiddle DEMO

Add this to your CSS:

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

jQ:

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

BTW: on TC page it's just a CSS play with z-indexes. nothing more. all elements are visible at page load, it's just the scroll that makes appear a z-index lower element beneath the big logo.

In plain Javascript would be like 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" ;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...