简体   繁体   中英

Add class to individual elements when in viewport

I currently have a script set up to add a class to a div once its in the viewport. I have multiple divs that this applies to however, so once the first one is visible, the class gets added to every single one. Is there a more streamline way of separating these rather than duplicating the function for each element?

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

You're running the function for all instances of .header-title span . Instead, do each individually:

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

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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