在视口中时,将类添加到单个元素

时间:2016-12-16 19:01:51

标签: javascript jquery

我目前有一个脚本设置,一旦在视口中将一个类添加到div中。我有多个div适用于此,所以一旦第一个可见,该类就会被添加到每一个。是否有更简化的方法来分离这些而不是复制每个元素的函数?

HTML

<div class="header-title"><span>FOO</span></div>

<div class="header-title"><span>BAR</span></div>

CSS

.header-title span {
  display: inline-block;
  position: relative;  
}

.change:after {
  content: " ";
  position: absolute;
  height: 5px;
  border-bottom: 1px solid red;
  -webkit-animation: extend .75s 1 forwards;
  animation: extend 4s 1 forwards;
  margin-left: 4px;
  top: 1.2em !important;
}


@-webkit-keyframes extend {
  0% {
    width: 0;
  }
  100% {
    width: 200px;
  }
}
@keyframes extend {
  0% {
    width: 0;
  }
  100% {
    width: 200px;
  }
}

的jQuery

function isElementInViewport(elem) {
    var $elem = jQuery(elem);

    // Get the scroll position of the page.
    var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
    var viewportTop = jQuery(scrollElem).scrollTop();
    var viewportBottom = viewportTop + jQuery(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) && (elemBottom > viewportTop));
}

// Check if it's time to start the animation.
function extendLine() {
    var $elem = jQuery('.header-title span');

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

    if (isElementInViewport($elem)) {
        // Start the animation
        $elem.addClass('change');
    }
}

// Capture scroll events
jQuery(window).scroll(function(){
    extendLine();
});

http://codepen.io/SeanLindsay1/pen/bBOWLW

1 个答案:

答案 0 :(得分:1)

您正在为.header-title span的所有实例运行该功能。相反,分别做每个人:

function extendLine() {
    jQuery('.header-title span').each(function() {
        var $elem = this;
        ...
    });
}

Demo