简体   繁体   English

使用iScroll将类添加到当前页面

[英]Add class to current page using iScroll

As the title suggests, I'm trying to add a class to the current 'snapped-to' element. 正如标题所示,我正在尝试将一个类添加到当前的“snapped-to”元素中。 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 jsfiddle演示

    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');

  });
}

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

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