当div内容在视口外时滚动

时间:2013-11-16 01:54:56

标签: javascript jquery viewport scrollto

我有一个像这样的简单代码

http://jsfiddle.net/QTa2c/

我想要的是,当用户点击列表中的一些最后一个元素来显示内容时,

$('a.showMeThis').click(function() {
   $(this).next('.content').slideToggle('fast', function() {
       // there's go all the magic
   });
});

并且它在视口之外(部分或全部) - 滚动div的高度,这样他就可以看到所有的内容。

我正在为此寻找一些逻辑,使用position()。顶部,window.innerHeight等,但它永远不会像我想要的那样......

希望你们能帮助我,保重并度过美好的一天!

2 个答案:

答案 0 :(得分:4)

使用.animate().offset()

$('a.showMeThis').click(function () {
    var $this = $(this);
    $this.next('.content').slideToggle('fast', function () {
        $('html,body').animate({
            scrollTop: $this.offset().top
        }, 'slow');
    });
});

Fiddle Demo

<小时/> 在OP的评论

之后更新

Updated Fiddle Demo

$('a.showMeThis').click(function () {
    var $this = $(this);
    $this.next('.content').slideToggle('fast', function () {
        if ($this.position()) {
            if ($this.position().top + $this.height() > $(window).scrollTop() + (window.innerHeight || document.documentElement.clientHeight)) {
                $('html,body').animate({
                    scrollTop: $this.position().top - (window.innerHeight || document.documentElement.clientHeight) + $this.height() + 15 + $this.next('.content').height()
                }, 100);
            }
        }
    });
});

答案 1 :(得分:2)

条件如下:http://jsfiddle.net/QTa2c/1/

if ($(this).parent().offset().top + $(this).height() > window.innerHeight + $(window).scrollTop())
          {
              var a = $(this)
              $('html,body').animate({scrollTop: $(a).parent().offset().top})
          }

我认为,这段代码足以理解逻辑=)

UPD:请注意,您应该将return false;插入.click事件,以防止跳转到#锚点。

相关问题