jQuery – 分别处理同一个类的多个实例?

目标:

  1. 我正在尝试创建一个视差滚动效果。

  2. 视差容器的实现方式如下:

  3. 当它的容器滚动到视图中时,我需要启动视差效果。

  4. 离开视图后 ,效果需要停止。

问题:

到目前为止jQuery工作得很好。

但是:因为我可以在一个页面上多个视差容器 (例如一个在顶部,一个在底部),我需要它们由jQuery 独立处理。

目前效果是……

  • 1.)一旦第一个视差容器滚动到视图中,就触发每个视差容器
  • 2.)每个视差容器离开视野后停止。

所以还不是解决方案。

思考

我认为它应该适用于jQuerys .each(),但到目前为止我无法真正开始工作。

当我尝试实现它时,我想我在某处混淆了嵌套函数。

这是我目前的代码:

 $(document).ready(function(){ $.fn.is_on_screen = function(){ var win = $(window); var viewport = { top : win.scrollTop(), left : win.scrollLeft() }; viewport.right = viewport.left + win.width(); viewport.bottom = viewport.top + win.height(); var bounds = this.offset(); bounds.right = bounds.left + this.outerWidth(); bounds.bottom = bounds.top + this.outerHeight(); return (!(viewport.right  bounds.right || viewport.bottom  bounds.bottom)); }; $(window).scroll(function(){ // Bind window scroll event if( $('.parallax').length > 0 ) { // Check if target element exists in DOM if( $('.parallax').is_on_screen() ) { // Check if target element is visible on screen after DOM loaded // ANIMATE PARALLAX EFFECT // If Parallax Element is scrolled into view do... // Variables var speed = 2.5; var calc = (-window.pageXOffset / speed) + "px " + (-window.pageYOffset / speed) + "px"; var container = $(".parallax"); // Function container.css({backgroundPosition: calc}); } else { // ...otherwise do nothing } } }); }) 

假设你想要做的滚动是相同的(使用相同的视差方法等),你可以在类上使用.each。 例:

 $(window).scroll(function(){ // Bind window scroll event $( ".parallax" ).each(function() { if( $( this ).is_on_screen() ) { // Check if target element is visible on screen after DOM loaded // ANIMATE PARALLAX EFFECT // If Parallax Element is scrolled into view do... // remember to replace ('.paralax') with (this) // Variables var speed = 2.5; var calc = (-window.pageXOffset / speed) + "px " + (-window.pageYOffset / speed) + "px"; var container = $( this ); // Function container.css({backgroundPosition: calc}); } else { // ...otherwise do nothing } }); });