div上的中心视口,而不是视口中的div

时间:2015-02-03 23:22:39

标签: jquery

我正在建立一个自动溢出的列表。目前,当单击列表时,它会展开以通过jquery显示更多内容。当它使用最初位于屏幕视口下方的列表元素时,它会转到顶部,您必须滚动才能看到您单击的内容。有没有办法阻止屏幕移动或以点击的元素为中心,以便它保持在视图中?

代码如下:

       $('.expand').click(function() {
              $(".expanding-tab").hide();
              $(this).siblings('.expanding-tab').toggle();
              $('.main-tab').removeClass('tab-highlight');
              $(this).children('.main-tab').toggleClass('tab-highlight');
        });

1 个答案:

答案 0 :(得分:1)

下面提供的代码完全基于this link,它提出了一种将浏览器视图滚动到元素位置的方法。它包含一些小调整,以适应askek的问题。我还对代码进行了广泛的评论,因为链接缺乏严格的解释。

// jQuery.fn is shorthand for jQuery.prototype and allows
// for the extension of the jQuery function set with
// custom functions.
// See: http://stackoverflow.com/questions/4083351/what-does-jquery-fn-mean
jQuery.fn.scrollView = function() {
    return this.each(function() {
        // This gives us the amount of pixels that is between
        // the element and the top of the window.
        var margin_top = jQuery(this).offset().top

        // Here you can define an offset that leaves some space at the top
        // of the element
        var offset = 10px;

        // Calling .animate() on the body and html objects
        // makes the transition of these elements smooth (the duration
        // of the transition is provided in the second argument in ms)
        jQuery('html, body').animate({
            // Setting the scrollTop property makes the page scroll 
            // upwards by the specified amount pixels.
            // Setting scrollTop to margin_top makes the page scroll up
            // the exact amount of pixels to make the element appear
            // at the top of the window.
            scrollTop: margin_top + offset
        }, 200);
    });
}

将此函数添加到jQuery原型后,您现在可以在任何所需元素上调用它。

// Calling scrollView on the selected element(s) calls the function
// we defined above and makes the page scroll so that that element
// is now at the top (with an optional offset)
jQuery('#my-element').scrollView();

最后,您可以将它作为onClick事件添加到元素中:

// Bind an onClick event listener to all elements with the 'expand' class
jQuery('.expand').click(function(event) {
    // Optionally you can use preventDefault() if it fits your needs
    event.preventDefault();

    // Call the scrollView function on the clicked element
    jQuery(this).scrollView();
});