Scroll to Single Post

2019-07-17 21:51发布

I'm currently developing a website on Wordpress that requires sort of like a fluid single page layout.

Developing the custom templates for the index, single post and category pages is a breeze, but implementing it in such a way that when the user clicks on a post and the site scrolls downwards to display the single post custom template is not.

This is a reference site demonstrating this function - Nike Free Voice. What basically happens is that if you click an image, the site will scroll down to reveal the actual article/post.

I'm supposing that the most appropriate way is to use AJAX to load the content into a DIV and then have JQUERY to scroll the page down to that particular DIV. Question here is: How do I do that?

I've also considered scrolling down to an IFRAME but targeting the IFRAME source to the single.php file or the actual permalink won't work - doing so for the former just renders an error and doing so for the latter will mean that the content loaded in isn't dynamic because it is an absolute link to the permalink.

Really hope someone around would have an idea of where to start.

Thanks in advance guys!

PS: I haven't posted any sample codes because the infrastructure of Wordpress is pretty much standard. It's really just the matter of loading in the right single post content and then scrolling to it.

3条回答
ら.Afraid
2楼-- · 2019-07-17 22:15

How about setting an anchor at the desired location, then jumping to it?

<a name="someDiv">
<div><img ... ></div>

And to jump to it:

window.location.hash="someDiv";

It's even bookmarkable!

查看更多
3楼-- · 2019-07-17 22:20

This function takes in a target element, which should be the div containing the post, and a duration, if you want to animate the scrolling.

function scrollToElement(element, duration){
 var verticalScrollTarget = element.offset().top;
 if(typeof duration == 'undefined'){
    $('html,body').scrollTop(verticalScrollTarget);
  }else{
    $(($('html').scrollTop() != 0 ? 'html':'body')).animate({scrollTop: verticalScrollTarget}, duration)
  }
}

Example:

    $.ajax({ 
      url: '/someurl',
      success : function(response){
         var target = $('div',response);
         $('#somePostList').append(response);
         scrollToElement(target, 1000);
      });
查看更多
一纸荒年 Trace。
4楼-- · 2019-07-17 22:24

I've resolved the issue at another post (Load Wordpress post Content into DIV using AJAX / JQUERY) that was specifically targeted at loading the content in using AJAX and JQUERY based on Emanuele Feronato's post

查看更多
登录 后发表回答