繁体   English   中英

查找与视口中元素的类匹配的html5数据属性

[英]Find html5 data attribute which matches the class of the element in viewport

我有一个侧面导航菜单,其链接如下所示:

<div class="side_nav_feature_cont scrollElement" id="scrollE5">
<a class="pageScroller" data-scrollto="sec5">
    <span class="side_nav_feature_item">Develop and Nurture your Talent</span>  
    </a>
</div>

单击它们时,将滚动到带有如下所示锚点的部分:

<div class="sec5 sectionAnchor"></div>

脚本的滚动部分运行正常,但是我还想在侧面导航项进入视口一半时向其添加一个活动类。 我正在使用以下脚本检查项目何时已中途,但我仍然需要根据锚点的类别“查找”匹配的“数据滚动条”。

$(window).on('scroll', function() {
        var halfWay = $(window).height()/2; // get half height of window
        $('.sectionAnchor').each(function() { // check each section anchor
            var distance = $(this).offset().top - halfWay; // check when halfway from top
            if ($(window).scrollTop() >= distance) {
                // I want to find the matching data-scrollto here and add an active class
            }
        });

是否可以将sectionAnchor类中的“ sec5”与导航项的数据滚动条“ sec5”进行匹配?

我使用了这个小jquery函数,该函数只是检查以查看指定的data属性是否匹配给定的值。

$.fn.filterByData = function (name, value) {
    return this.filter(function () {
        return $(this).data(name) === value;
    });
};

因此,假设锚标记的数据属性中的类始终是列表中的第一类,您的代码将类似于以下内容:

$(window).on('scroll', function () {
    var halfWay = $(window).height() / 2; // get half height of window
    $('.sectionAnchor').each(function () { // check each section anchor
        var distance = $(this).offset().top - halfWay; // check when halfway from top
        if ($(window).scrollTop() >= distance) {
            var classString = $(this).attr('class');
            if (classString) {
                //Get first class from class string
                var target = classString.split(' ')[0];
                //Find anchors and filter by data-scrollto == our class name
                var navItem = $('.pageScroller').filterByData('scrollto', target);

                navItem.addClass('active');
            }
        }
    });
});

尝试使用match函数从sectionAnchor获取类。 然后使用属性选择器获得正确的菜单选项。

$(window).on('scroll', function() {
        var halfWay = $(window).height()/2; // get half height of window
        $('.sectionAnchor').each(function() { // check each section anchor
            var distance = $(this).offset().top - halfWay; // check when halfway from top
            if ($(window).scrollTop() >= distance) {
                // I want to find the matching data-scrollto here and add an active class
                var id = $(this).attr('class').match(/(sec\d*)/)[0];
                $('a.pageScroller[data-scrollto="' + id + '"]').addClass('active');
            }
        });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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