Javascript滚动激活

时间:2016-04-20 18:18:12

标签: javascript html css animation scroll

我的朋友给了我一个网页,帮助我学习一些Javascript,他做了一个页面,一旦用户滚过div的顶部,每个div的内容就变得可见了。问题是内容显示为最晚,因此我想让用户在其上方部分向下滚动80%或下一部分的-20%时激活动画。 对于长篇大论的解释感到抱歉,但很难描述,请看一下jsfiddle,你会理解我的意思。

此处the fiddle

    <script>

function scrollContent(){

//store the header as a variable
var header = document.getElementById("header");

//IMPORTANT NOTE ABOUT ARRAYS:
//the first item in an array isnt the "1"st itemm its the "0"th.
//so to select the first item, you say sections[0], to select the second item, you say sections[1] etc etc.

//get all of the elements with the class "section"
//and store them in an array
var sections = document.getElementsByClassName("section");

//do the same as above, for the "content" elements.
var contents = document.getElementsByClassName("content");

//get the height of the page
//which, because of our css, is also the height of one section
var height = window.innerHeight;

//get users position on the page
var ypos = window.pageYOffset; 

//which section the user is currently on
//we work this out by dividng the user's position on the page
//by the height of the actual page (which is the same height as one section)

//for example, if the user is 1000 pixels down and the page is 500 pixels high,
//1000 divided by 500 is 2, so they are on the second section.
//we wrap the sum in Math.floor() to round it down to the nearest whole number
var currentSection = Math.floor(ypos / height);

//stops the animation breaking when people try to scroll above the top of the page
if(currentSection < 0){
    currentSection = 0;
}



//loop through all of the sections
for(var i = 0; i < sections.length; i++){
    //if the section is currently in view
    if(i <= currentSection){
        //make the content viewable
        contents[i].style.opacity = "1";
    //if not
    } else {
        //hide the content
        contents[i].style.opacity = "0";
    }
}

}

window.addEventListener("scroll", scrollContent);
scrollContent();

</script>

2 个答案:

答案 0 :(得分:1)

您可以将var ypos(用户滚动位置)更改为:

var ypos = window.pageYOffset + Math.floor(height * 0.2);

其中* 0.2height / window.innerHeight值的20%。所以它实际上只是将20%高度的缓冲区添加到滚动位置,这允许(不透明度)代码的其余部分提前渲染,所以说出来

您可以将0.2值更改为您喜欢的任何内容,以便在滚动期间迟早显示内容。

答案 1 :(得分:0)

添加JS。检查你的innerHeight属性