首页 > 解决方案 > 滚动更改部分 javascript

问题描述

我想创建一个页面,当用户在浏览器中使用鼠标或滚动条滚动到底部时,一个部分会发生变化,它也有 400 或任意数字。

同样,当用户滚动到顶部时,此更改将撤消。

滚动底部时

<h1>hello<h1> <!-- show 400px scroll bottom -->
<h1>my dear<h1><!-- show next 400px scroll bottom  mean 800px -->
<h1>friend<h1><!-- show next 400px scroll bottom mean 1200px -->

滚动到顶部时

<h1>friend<h1><!-- show next 400px scroll top mean 1200px -->
<h1>my dear<h1><!-- show  next 400px scroll top mean 800px -->
<h1>hello<h1> <!-- show  400px scroll top mean 400px -->

我的html代码是

<div class="box">
<h1>hello<h1>
<h1>my dear<h1>
<h1>friend<h1>
</div>

我只想用 javascript 来做这件事

标签: javascripthtml

解决方案


you can use this code




window.onscroll = function() {myFunction()};

function myFunction() {
  var winScroll = document.body.scrollTop || document.documentElement.scrollTop; // this is must to minus from a OfsetTop section before this
    var element = document.querySelectorAll('h1');
 console.log(Math.round(winScroll)); 
    for(var i = 0; i < element.length; i++){
        var min = 500 * i;
        var max = (1000 * i)-(500 * (i-1));
//         console.log(Math.round(winScroll));
    if(winScroll >= min && winScroll < max){
        element[i].className = "show";
         console.log(Math.round(winScroll)); 
    }else{
         element[i].className = 'hide';

    } 


    }


}





推荐阅读