gpt4 book ai didi

javascript - 在视口(viewport)中为单个元素添加类

转载 作者:行者123 更新时间:2023-11-29 15:24:06 25 4
gpt4 key购买 nike

我目前设置了一个脚本,用于在 div 进入视口(viewport)后将其添加到 div。但是,我有多个适用于此的 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

最佳答案

您正在为 .header-title span 的所有实例运行该函数。相反,每个单独做:

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

Demo

关于javascript - 在视口(viewport)中为单个元素添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41190847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com