为每个包含类的元素执行 jQuery 函数

execute jquery function for each element containing class

本文关键字:执行 jQuery 函数 元素 包含类      更新时间:2023-09-26

下面的函数大部分工作 - 它根据需要移动背景,但是我希望该函数在任何具有"animate"类的元素上运行,而不必调用每个元素底部。我尝试了$('.animate').load(function(){};但它就是不起作用...谢谢

JAVASCRIPT

$(window).load(function(){
(function(){
      $.fn.move = function(){
            var $this = $(this);
            var offset = $this.offset().top;
            var start = 0;
            var end = offset + $this.height();
            var speed = $this.attr("speed");
            return this.each(function(){
                  $(window).bind('scroll', function() {
                       var windowPos = $(window).scrollTop();
                        if((windowPos >= start) && (windowPos <= end)) {
                              var newCoord = windowPos * speed;
                              $this.css({'background-position': '0 '+ newCoord + 'px'});
                        };
                  });
            });
      };
})(jQuery);
$('.animate').move();
});

.HTML

<div class="welcome_6"></div>
    <div class="welcome_5"></div>
    <div class="welcome_4"></div>
    <div class="welcome_3"></div>
    <div class="welcome_2 animate" speed="-1"></div>
    <div class="welcome_1 animate" speed="0"></div>

编辑:当我滚动页面时,元素会根据滚动位置移动。每个元素以不同的速度移动(设置为 html 属性)。此代码以相同的速度移动它们。 我假设 $('.animate') 应该在顶部的某个地方替换 $.fn.move,但我无法弄清楚。

应该$('.animate')而不是$('animate')注意查询开头的点,它向 jQuery 表示您正在寻找一个类。

我认为问题在于您在加载函数中使用立即调用的函数的方式,并且您在底部传递jQuery而不是立即调用函数。只要您的脚本标签放置在 jquery 脚本标签之后,这将更新背景位置

这是js fiddle的链接:

更新:https://jsfiddle.net/kriscoulson/pnrx34wp/1/

我没有您的确切样式代码,所以我即兴创作,但如果您检查元素,背景位置正在更新;

和更新 :

$.fn.move = function() {
  var $this = $(this);
  var offset = $this.offset().top;
  var start = 0;
  var end = offset + $this.height();
  return this.each(function(index, element) {
    var $element = $(element);
    var speed = $element.attr("speed");
    $(window).bind('scroll', function() {
      var windowPos = $(window).scrollTop();
      if ((windowPos >= start) && (windowPos <= end)) {
        var newCoord = windowPos * speed;
        $element.css({
          'background-position': '0 ' + newCoord + 'px'
        });
      };
    });
  });
};
$(document).ready(function() {
  $('.animate').move();
});

编辑:您的"this"绑定已关闭,您的速度在this之外声明。