简体   繁体   English

使Javascript / JQuery视差幻灯片效果可用于类

[英]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: 我有以下脚本,并且希望使其也可用于类,而不仅仅是id:

<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: 我也曾尝试将其更改为JQuery(至少我想我希望这样做),但均无效:

<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/ 第一个示例有效: http//jsfiddle.net/ecb3744t/

2nd example doesn't work http://jsfiddle.net/3mc4dcus/ 第二个示例不起作用http://jsfiddle.net/3mc4dcus/

3rd example doesn't work http://jsfiddle.net/wvtqke36/ 第三个示例不起作用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. 您的小提琴不包含jQuery,并且您的代码中存在语法错误。

Fiddle: modified example 3 小提琴: 修改示例3

If you don't want to use jQuery, then use this code: 如果您不想使用jQuery,请使用以下代码:

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. 请注意,document.getElementsByClassName()返回一个元素数组。 Therefore you'll have to loop through each of these elements and apply the transformation. 因此,您将必须遍历所有这些元素并应用转换。

Fiddle: modified example 1 小提琴: 修改示例1

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM