简体   繁体   中英

Div Position: Fixed. Absolute when certain length away?

I'm currently making a website with a "Support is Live" div which will be following the user when scrolling. So I gave it Position: Fixed; and all works fine.

But when the user scrolls back up, I want the Support div to stop so it doesn't "touch" the header.

Here is a picture that hopefully makes it easier to understand:

http://gyazo.com/2694b03181a39c3b6673901b42b5952d I want the yellow div to stop in line with the orange field on the picture. But when the user starts to scrolling down again, it will follow.

My Best Regards Philip

This will need some JQuery to work properly: JSFIDDLE

JQuery

$(document).on("scroll", function() {    
  if($(document).scrollTop() < 100) { 

 $('#alert').addClass("absolute");

} else if($(document).scrollTop() > 100) {  //100 is the height of your header. Adjust if needed
 $('#alert').removeClass("absolute");

} 
});

CSS

.absolute {
top: 100px; //same as the value in the conditions
position: absolute;

}


#alert{

background-color: #FF0;     
float: left;    
height: 400px;  
width: 230px;   
margin-left: 20px; 
    position: fixed;
z-index:999;


}

HTML

<div id="alert" class="absolute"> </div> 
/!-- add the class so that it doesn't mess up the layout when you load the page --!/

The srolltop function checks how much space is between your viewport and the top of your document. When it reaches the height of the header, a class absolute is applied in order to keep the #alert div in its place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM