开发者

Jquery scroll stops short of page bottom

I am using jquery to scroll to sections of my page.

Here's the code:

// Scroll to element
$('#menu li a').click(function(){        
    var elementId = $(this).attr('href');   
    $('html, body').animate({ scrollTop: $(elementId).offset().top }, 1600);
    return false;
    });

<ul id="menu">
  <li><a href="#item1">1</a></li>
  <li><a href="#item2">2</a></li>
</ul>

<div id="item-1">placeholder-1</div>
<div id="item-2">placeholder-2</div>

As you can see I'm grabbing the href (#id) of an target element from the menu link and scrolling to the target element.

But the issue lies in the fact that I have target elements going right to the bottom of the page, and when the page is scrolled to the last, the top of that element can't scroll to the top of the page as there is not enough page left at bottom... Am I making sense?

I'm trying to work out a solution using css 开发者_Python百科or jquery that would mean that regardless of the height of the page (or padding/margin at bottom) the element will be at the top of the viewport when a menu item is clicked.

Do I add more padding based on the height of the viewport using javascript? Do I use some kind of overflow trick?


Your problem is that the page isn't as tall as you want it to be. If you try to go to #x and #x is at the bottom of <body>, then you'll scroll to the bottom of the page and #x will be at the bottom of the window when you want it at the top.

I think your only choice is to force the <body> to be taller. Something like this:

$(document).ready(function() {
    viewport_height = $(window).height();
    $height_hack    = $('<div>&nbsp;</div>').height(viewport_height);
    $('body').append($height_hack);
});

Something like that will append a (visually) empty <div> to the bottom of your content, this extra <div> will have the same height as the browser's viewport and this extra height will let you always scroll your elements right to the top of the viewport.


I think there's a lot of things you can do to solve this but I would use CSS min-height Property to body. I believe this is more a personal answer, so you can do whatever you want, as you said, add padding, margin...

But I would set a minimum height in a way the screen can scroll to the items you want it to.


Update

Hmm, right. I didn't think about dynamic content. If the content gets bigger the body minimun height will probably not solve the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜