简体   繁体   中英

Make Javascript / JQuery parallax slide effect work for classes

I have the following script, and would like to make it work also for classes instead of id's only:

<script>
function parallax(){
var prlx_1 = document.getElementById('banner-welcome');
prlx_1.style.top = -(window.pageYOffset / 8)+'px';
}
window.addEventListener("scroll", parallax, false);
</script>

I have tried to do the following, but it does not work:

<script>
function parallax(){
var prlx_1 = document.getElementsByClassName('banners');
prlx_1.style.top = -(window.pageYOffset / 8)+'px';
}
window.addEventListener("scroll", parallax, false);
</script>

I have also tried to change it to JQuery (at least I think I hope I did), neither does it work:

<script>
var prlx = $('.banners');
$(window).on('scroll', function () {
prlx.css({ 'top': -(window.pageYOffset / 8)+'px' });
});
});
</script>

Here are the two examples, one works, one does not:

1st example works: http://jsfiddle.net/ecb3744t/

2nd example doesn't work http://jsfiddle.net/3mc4dcus/

3rd example doesn't work http://jsfiddle.net/wvtqke36/

I've modified your third example and this should work:

var prlx = $('.banners');
$(window).on('scroll', function () {
    $(prlx).css({ 'top': -(window.pageYOffset / 2)+'px' }); 
});

Your Fiddle did not include jQuery and you had a syntax error in your code.

Fiddle: modified example 3

If you don't want to use jQuery, then use this code:

function parallax(){
    var prlx = document.getElementsByClassName('banners');
    for(var i=0; i < prlx.length; i++) {
        var elem = prlx[i];
        elem.style.top = -(window.pageYOffset / 2)+'px';        
    }
}
window.addEventListener("scroll", parallax, false);

Note that document.getElementsByClassName() returns an array of elements. Therefore you'll have to loop through each of these elements and apply the transformation.

Fiddle: modified example 1

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