javascript - 如何使用 jquery 将类添加到仅匹配条件的一个元素?

标签 javascript jquery css

我正在尝试检查元素是否越过视口(viewport)的底部边缘。如果是这样,我想将类 start 添加到此元素。问题是当条件满足时,类添加到所有 h2 元素。

这是我的代码:

$.fn.checkAnimation = function() {

  var context = this;
  function isElementInViewport(elem) {
    var $elem = context;

    // Get the scroll position of the page.
    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

    // Get the position of the element on the page.
    var elemTop = Math.round( $elem.offset().top );
    var elemBottom = elemTop + $elem.height();

    return (elemTop < viewportBottom);
  }

  // Check if it's time to start the animation.
  function checkAnimation() {
      console.log(isElementInViewport($elem));
      var $elem = context;

      // If the animation has already been started
      if ($elem.hasClass('start')) return;

      if (isElementInViewport($elem)) {
          // Start the animation
          context.addClass('start');
      }
  }
  checkAnimation();
  return this;
};
$(window).on('scroll scrollstart touchmove orientationchange resize', function(){
      $('h2').checkAnimation();
  });

最佳答案

您需要更改您的 checkAnimation jQuery 插件以循环遍历 jQuery 对象中的所有元素并单独处理它们或像这样调用您的函数

$('h2').each(function(){
    $(this).checkAnimation();
}

这就是我所说的在插件中单独处理元素的意思:

$.fn.checkAnimation = function() {

    function isElementInViewport($elem) {
        var viewportTop = $(window).scrollTop();
        var viewportBottom = viewportTop + $(window).height();

        var elemTop = Math.round( $elem.offset().top );
        var elemBottom = elemTop + $elem.height();

        return (elemTop < viewportBottom);
    }

    function checkAnimation() {
        var $elem = $(this);
        if ($elem.hasClass('start')) return;

        if (isElementInViewport($elem)) {
           $elem.addClass('start');
        }
     }
     return this.each(checkAnimation);
};

如果你使用这个版本的插件,你可以这样调用它:

$('h2').checkAnimation();

它只会将类添加到与条件匹配的元素,而不是您调用该函数的 jQuery 对象中的所有元素。

关于javascript - 如何使用 jquery 将类添加到仅匹配条件的一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47249012/

相关文章:

javascript - 这是 JavaScript 原型(prototype)继承模型中的缺陷吗?

javascript - 在 javascript 中使用负向后查找来转义@@

jQuery 变量到 ID 问题

javascript - VB.NET smtp.Send 的 jQuery/JavaScript 替代方案

jquery - 将表单中多个输入框的值复制并连接到一个输入字段

jQuery 悬停仅适用于第二次悬停

javascript - Date.toLocaleString() 的 Chrome 时区选项

javascript - 循环中 PHP 数组到 Javascript

php - CSS 背景图片未加载,似乎找不到图片

css - 如何仅在手机或平板电脑 View 上显示菜单?