簡體   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