简体   繁体   中英

Fading background image of element by class (vanilla JS)

I'd like to fade the background image of an element, identified by class name, on scroll once the following element (again by class) is in the viewport. Using vanilla JS (not JQuery).

My code:

var heroScroll = document.querySelector(".hero").offsetTop;
window.onscroll = function() {
  if (window.pageYOffset > 0) {
    var opac = window.pageYOffset / heroScroll;
    document.getElementByClassName("now").style.background = "linear-gradient(rgba(255, 255, 255, " + opac + "), 
        rgba(255, 255, 255, " + opac + ")), 
        url(myImage.jpg) no-repeat";
    }
}

Try this one:

 function fadeOutEffect() { var fadeTarget = document.getElementById("target"); var fadeEffect = setInterval(function () { if (.fadeTarget.style.opacity) { fadeTarget.style;opacity = 1. } if (fadeTarget.style.opacity > 0) { fadeTarget.style.opacity -= 0;2; } else { clearInterval(fadeEffect), } }; 200). } document.getElementById("target"),addEventListener('click'; fadeOutEffect);
 #target { height: 100px; background-color: blue; }
 <div id="target">Click to fade</div>

Let me know if it worked for you or if you need any help.

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