質問

So here's what I'm trying to do, I have a sticky navigation at the top of a page with a background that's transparent. But when the user scrolls down and the content is underneath the navigation, I want to change the background of the navigation so it is NOT transparent. Now I've already achieved this, but my question is: is it possible when the user scrolls back to the top of the page for the navigation background to become transparent again?

For example: user loads page, navigation is transparent, user scrolls down, navigation background turns NON transparent, then user scrolls back to top of page. Is it possible to make the navigation background become transparent again? Also I am trying to achieve this without using jquery! So answer only in raw javascript please!

___JS___
window.onscroll = function nav_bg(){
var header = document.getElementById("header");
header.setAttribute('style','background-color:rgba(0,0,0,1);')
}


___CSS___
#header{background-color:rgba(0,0,0,.4);}

This is my current code, but when the user scrolls back to the top, the background stays non-transparent.

役に立ちましたか?

解決

This is how jQuery does it:

var doc = document.documentElement, body = document.body;
var left = (doc && doc.scrollLeft || body && body.scrollLeft || 0);
var top = (doc && doc.scrollTop  || body && body.scrollTop  || 0);

Once you know where the window is scrolled to you just need to bind to the "scroll" event (Binding is a bit trickier without jQuery only because older browsers have different methods for dealing with event binding)

var addEvent = (function( window, document ) {
 if ( document.addEventListener ) {
  return function( elem, type, cb ) {
   if ( (elem && !elem.length) || elem === window ) {
    elem.addEventListener(type, cb, false );
   }
   else if ( elem && elem.length ) {
    var len = elem.length;
    for ( var i = 0; i < len; i++ ) {
     addEvent( elem[i], type, cb );
    }
   }
  };
 }
 else if ( document.attachEvent ) {
  return function ( elem, type, cb ) {
   if ( (elem && !elem.length) || elem === window ) {
    elem.attachEvent( 'on' + type, function() { return cb.call(elem, window.event) } );
   }
   else if ( elem.length ) {
    var len = elem.length;
    for ( var i = 0; i < len; i++ ) {
     addEvent( elem[i], type, cb );
    }
   }
 };
}
})( this, document );
// Example Usage
addEvent( window, 'scroll', function() {
 //Test scroll position and set style
});

(This was taken from this page)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top