淡入Scroll Plain JavaScript No JQuery

时间:2017-07-27 14:52:39

标签: javascript

我尝试在滚动上实现与此https://codepen.io/hollart13/post/fade-in-on-scroll类似的文字淡入。

$(function(){  // $(document).ready shorthand
$('.monster').fadeIn('slow');
});

$(document).ready(function() {

/* Every time the window is scrolled ... */
$(window).scroll( function(){

    /* Check the location of each desired element */
    $('.hideme').each( function(i){

        var bottom_of_object = $(this).position().top + $(this).outerHeight();
        var bottom_of_window = $(window).scrollTop() + $(window).height();

        /* If the object is completely visible in the window, fade it it */
        if( bottom_of_window > bottom_of_object ){

            $(this).animate({'opacity':'1'},1500);

        }

    }); 

});

});

但是,我不想使用JQuery。我想用纯JavaScript完成这个。不幸的是,大多数在线示例都是基于JQuery的,并且使用普通的JavaScript很少。

这是我到目前为止所尝试过的"翻译"这个JQuery变成了普通的JS。它不起作用。任何人都可以指出我出错的地方吗?

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

function myFunction() {
var elements = document.getElementsByClassName("target");

for(var i = 0; i < elements.length; i++){
var bottomOfObject = elements[i].getBoundingClientRect().top + 
window.outerHeight;

var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : 
(document.documentElement || document.body.parentNode || 
document.body).scrollTop;

var bottomOfWindow = scrollTop + window.innerHeight;

if(bottomOfWindow > bottomOfObject){
  $(this).animate({'opacity': '1'}, 1500);
}
}
console.log(bottomOfObject);
}

提前致谢!

2 个答案:

答案 0 :(得分:0)

试试这个简单的vanilla JavaScript解决方案

&#13;
&#13;
var header = document.querySelector("#header");

window.onscroll = function() {
  if (document.body.scrollTop > 50) {
    header.className = "active";
  } else {
    header.className = "";
  }
};
&#13;
#header {
  background-color: black;
  transition: all 1s;
  position: fixed;
  height: 40px;
  opacity: 0;
  right: 0;
  left: 0;
  top: 0;
}

#header.active {
  opacity: 1;
}

#wrapper {
  height: 150vh;
}
&#13;
<html>

<body>
  <div id="header"></div>
  <div id="wrapper"></div>
</body>

</html>
&#13;
&#13;
&#13;

基本上有一个位于屏幕顶部的元素,最初是不可见的(不透明度为0),并且使用javascript我添加一个类使其可见(不透明度1)使得它慢慢可见而不是立即显示是过渡:全是1;

答案 1 :(得分:0)

这是我的基于滚动位置的动态不透明度的版本,我希望它有所帮助 Window Vanilla Scroll

function scrollHandler( event ) { 

        var margin = 100;
        var currentTop = document.body.scrollTop;
        var header = document.querySelector(".header");
        var headerHeight = header.getBoundingClientRect().height;
        var pct = (currentTop - margin) / ( margin + headerHeight );
        header.style.opacity = pct;
        if( pct > 1) return false;
    }

    function addListeners() { 
        window.addEventListener('scroll' , scrollHandler );
        document.getElementById("click" , function() { 
            window.scrollTop = 0;
        });
    }
    addListeners();