jQuery: using class name selectors with the animat

2019-08-24 04:38发布

I have just discovered Barba.js and find it very useful. It provides smooth transitions between URLs of the same website.

I have put together a Plunker consisting of two pages (index.html and about.html) that are loaded smoothly, with the help of jQuery's fadeIn() and fadeOut() methods.

I would like the About us page to not only be faded in, but scrolled down some 250px too.

For this purpose, I have:

  1. added a class to the html tag in the About Us page: <html class="about">
  2. added this in the script.js:

    $('html.about, html.about body').animate({ scrollTop: 300 },1000);

Evan though the page scrolls if no class name selector is mentioned in the script, the version above does not work. But I want only the "About Us" page to be animated.

What shall I change?

1条回答
ら.Afraid
2楼-- · 2019-08-24 04:45

The "About Us" page and the index page are displayed on the same page, a new html document is not rendered for each page. The content of each page is simply written over the previous one, ie inside the .barba-wrapper div element. So scrolling the page of one is going to "scroll the other one" as they are on the same page.

The <html> element stays the same between page switches, it never gets a class about. This is why your selector doesn't work to scroll the page.

If you want the page to be back at the top when going back simply animate it back to the top on Barba changing it. You can do this by:

  1. Adding an event listener for the linkClicked event
  2. Checking which page was clicked
  3. If not the about us page scroll the page to the top if needed

Barba.Dispatcher.on('linkClicked', function(link,event) {
   if(!link.href.includes('about.html') {
     $('html, html body').animate({
       scrollTop: 0
     },1000);
   }
});
查看更多
登录 后发表回答