简体   繁体   English

仅限原生JavaScript-滚动到视口时元素不透明度发生变化

[英]NATIVE JavaScript only - element opacity change when scrolled into viewport

I'm trying to make the elements on the page fade in on scroll. 我正在尝试使页面上的元素在滚动时淡入。 Easy enough right? 很容易吧? Not for me. 不适合我。

HTML is a standard list. HTML是标准列表。 CSS sets all elements to opacity 0 prior to scrolling. CSS在滚动之前将所有元素设置为不透明度0。

I'm trying to use Native JavaScript only. 我正在尝试仅使用本机JavaScript。

    // get current page body
    var actBody = document.getElementById('acts-body');

    // on scroll function
    actBody.onscroll = function(){

        // get screen height
        var screenPosition = window.innerHeight;
        // get all text elements
        var artistName = document.getElementsByClassName('artist');

        // loop through all elements
        for(var i = 0; i < artistName.length; i++){

            // get each elements position from top
            var positionFromTop = artistName[i].getBoundingClientRect().top;

            // if element is in viewport add class
            if(positionFromTop - screenPosition <= 0){
                artistName[i].classList.add('txt-fadeIn');
            }
            else{
                artistName[i].classList.remove('txt-fadeIn');
            }

            console.log(artistName[i]);
        }

i think it should solve it 我认为应该解决

            if(screenPosition  - positionFromTop  <= 0){
            artistName[i].classList.add('txt-fadeIn');
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在媒体查询中滚动到底部时如何更改元素的不透明度 - How to change opacity of element when scrolled to bottom within media query 当元素向上滚动到页面顶部时,我想将其不透明度从0更改为1 - I want to change opacity from 0 to 1 of the element when it's scrolled up to the top of the page 如何仅使用纯JavaScript对滚动元素进行简单的不透明度更改? - how to do a simple opacity change of an element on scroll with only pure javascript? 滚动页面时更改元素的高度将元素移动到视口之外 - Changing height of element moves element outside of viewport when page is scrolled 当另一个元素滚动到视口中时向按钮添加类 - adding class to button when another element is scrolled into the viewport 滚动到屏幕外时更改元素位置 - change element position when it scrolled out of screen 滚动到元素时执行FadeInUp动画(javascript) - Do FadeInUp animation when Scrolled to element (javascript) 如何使用JavaScript动态更改元素的不透明度 - How to change the opacity on an element dynamically using javascript 使Javascript事件仅在滚动到时发生 - Make Javascript event happen only when scrolled to 如何应用于多个元素:仅当父元素在视口中时,JavaScript 才会对元素产生滚动效果 - How to apply to many elements: JavaScript scroll effect on element only when parent element is in viewport
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM