简体   繁体   中英

Add class to current page using iScroll

As the title suggests, I'm trying to add a class to the current 'snapped-to' element. With this:

var verticalScroll;
verticalScroll = new IScroll('#wrapper', {
    snap: true
});
verticalScroll.on('scrollEnd', function(){
    alert(this.currentPage);
});

I get this alert when the scrolling is done:

[object Object]

So I was thinking I could use something like this to add a class:

verticalScroll.on('scrollEnd', function(){
    var newPage = this.currentPage;
    $(newPage).addClass('current');
});

But no joy. Done lots of searches to try and find the same situation. It must be something fairly simple.

Yeah, it's a little bit tricky. Some time ago I tried to add an "active" class to the link and the page. I ended up with this:

after scroll ended:

myScroll.on('scrollEnd', function () {
    addActiveClass();
});

the function:

function addActiveClass() {

    // get current page with iScroll
    var currentSection = myScroll.currentPage.pageY;

    // get current link and page
    var activeLink = $('nav a[href="' + currentSection + '"] span');
    var activeSection = $('section[class="' + currentSection + '"]');

    // remove active class from all links and pages
    $('nav a span, section').removeClass('active');

    // add active class to current link and page
    $(activeLink).addClass('active');
    $(activeSection).addClass('active');
}

Only one thing that annoys me, you have to give every section a page number as a class:

<section class="0"> … <section>
<section class="1"> … <section>
<section class="2"> … <section>

Same with links:

<a href="0"></a>
<a href="1"></a>
<a href="2"></a>

But maybe could be added dynamically somehow.

And don't forget option:

snap: 'section'

jsfiddle demo

    var workCase;

function loadcase() {
  workCase = new IScroll('#work-case', {
    mouseWheel: true,
    resizeScrollbars: true,
    snap: 'section',
    interactiveScrollbars: true,
    mouseWheelSpeed: 10,
    scrollX: true,
    scrollY: false,
    momentum: true,
    snapSpeed: 800,
    scrollbars: 'custom',
    wheelAction: 'scroll'
  });

  workCase.on('scrollEnd', function() {
    var sectionIndex = Number(this.currentPage.pageY);

    var iScrollConteiner = $('#work-case').children()[0];
    var dataNumber = $(iScrollConteiner)[0].children[sectionIndex].className;

    var activeSection = $('section[class="' + dataNumber + '"]');

    $('section').removeClass('active');
    $(activeSection).addClass('active');

  });
}

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