[英]jQuery - Find and scroll to an element dynamically based on its text content
我正在构建一个“术语破坏者”,该术语的顶部是术语表,下面是每个术语的单独div,其中包含该术语作为标题,并在其下进行解释。
我正在尝试编写一个函数,当您单击顶部的那些专业术语中的一个时,会找到带有该术语的div作为h3标题,并滚动到它。
我不知道这些术语会是什么,所以不能依赖硬编码。 某些术语实际上也可能包含另一个术语的所有字母-例如,一个术语可能是“知识产权”,而另一个则可能是“知识产权律师”。 因此,该功能需要找到完全匹配的内容。
到目前为止,我已经设法编写了一个函数,该函数可以转换为小写字母,并将单击的术语与同名的h3匹配。 我无法解决的是如何使用它来滚动到它。 有没有人有什么建议? 我完全可能走错路了。
术语术语示例列表:
<div class="jargonBusterDropDown">
<div class="textWrapper">
<p>attorney</p>
<p>copyright</p>
<p>chartered</p>
<p>intellectual property</p>
<p>intellectual property lawyer</p>
<p>licensing</p>
</div>
</div>
完整术语div的示例
<div class="fullWidthContentCard jargonBusterCard">
<div class="fullWidthContentCard__title">
<h3>Attorney <i class="fa fa-chevron-down" aria-hidden="true"></i></h3>
</div>
<div class="fullWidthContentCard__content">
<p>DESCRIPTION GOES HERE</p>
</div>
</div>
我的JS
$('.jargonBusterDropDown p').click(function(){
var val = $(this).text().toLowerCase();
var titles = [];
$('.fullWidthContentCard__title h3').each(function(i, e){
titles.push($(e).text().slice(0, -1).toLowerCase());
});
var elementToScrollTo = titles.filter(function(title){
return val === title;
});
elementToScrollTo = elementToScrollTo.toString();
});
$('html, body').animate({scrollTop: $(object).offset().top}, 300 /*duration in milisec*/);
object
是您找到的object
。 如果您在each()函数中,则应编写this
。
编辑:完整的解决方案:
$(document).ready(function(){
$('.jargonBusterDropDown p').click(function(){
var val = $(this).text().toLowerCase();
console.log(val);
$('.fullWidthContentCard__title h3').each(function(i, e){
if($(e).text().slice(0, -1).toLowerCase().indexOf(val) >= 0) // val is found
{
console.log($(e));
$('html, body').animate({scrollTop: $(e).offset().top}, 300 /*duration in milisec*/);
return false; // Use this if you want to stop and scroll to the first object found. Otherwise you will scroll to the last.
}
});
});
});
您想找到要滚动到的元素,可以使用contains选择器 ,注意区分大小写!
之后,可以简单地滚动到使用element.offset().top
检索到的element.offset().top
的偏移量
$('.jargonBusterDropDown p').click(function() { var val = $(this).text().toLowerCase(); $('html, body').animate({ scrollTop: $('.fullWidthContentCard__title h3:contains(' + val + ')').offset().top }, 2000); });
.jargonBusterDropDown { margin-bottom: 1000px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="jargonBusterDropDown"> <div class="textWrapper"> <p>attorney</p> <p>copyright</p> <p>chartered</p> <p>intellectual property</p> <p>intellectual property lawyer</p> <p>licensing</p> </div> </div> <div class="fullWidthContentCard jargonBusterCard"> <div class="fullWidthContentCard__title"> <h3>attorney <i class="fa fa-chevron-down" aria-hidden="true"></i></h3> </div> <div class="fullWidthContentCard__content"> <p>DESCRIPTION GOES HERE</p> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.