仅当不在视图中时才滚动到元素 - jQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5685589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:38:36  来源:igfitidea点击:

Scroll to element only if not in view - jQuery

jqueryhtmlscroll

提问by Sergi Papaseit

I know a variation on this has been asked several times; I've been browsing SO for a while now but either I'm doing something wrong or I haven't found what I need.

我知道这方面的变化已经被问过好几次了;我已经浏览了一段时间,但要么我做错了什么,要么我没有找到我需要的东西。

I have a structure of nested comments, pretty much the same as the Facebook Comments plugin, and whenever replyis clicked, a small form with textarea and a button appear at the bottom of the comments.

我有一个嵌套评论的结构,与Facebook 评论插件几乎相同,每当reply点击时,评论底部会出现一个带有 textarea 和按钮的小表单。

Again, the behaviour is the same as the Facebook Comments pluginand I want to achieve the same when it comes to scrolling the newly add textarea into view.

同样,行为与Facebook Comments 插件相同,我希望在将新添加的 textarea 滚动到视图中时实现相同的效果。

I've tried the scrollToplugin, and it works smoothly but, even if I manually scroll to the very bottom of the page, the scroll animation will always reset the scroll position and begin from the top.

我已经尝试过scrollTo插件,它运行顺利,但是,即使我手动滚动到页面的最底部,滚动动画也会始终重置滚动位置并从顶部开始

For the record, this is how I'm calling scrollTo:

为了记录,这就是我调用 scrollTo 的方式:

$.scrollTo($('#addReply_1'), 800);

where addReply_1is the divcontaining the form. I've stried scrolling to the form itself and to the textarea. Same results.

其中addReply_1div包含表单。我已经尝试滚动到表单本身和textarea. 结果一样。

Is there a way to scroll to an element only if its not already visible?

有没有办法仅在元素尚未可见时滚动到该元素

I've tried many solutions offered on SO, like Scroll to an element using jQuery, but none seem to behave as desired; even Scroll to a particular element w/ jQueryor Check if element is visible after scrollingdisplays the same "jumpy" behaviour.

我已经尝试了很多在 SO 上提供的解决方案,比如使用 jQuery Scroll to an element,但似乎没有一个像预期的那样;甚至使用jQuery 滚动到特定元素在滚动后检查元素是否可见显示相同的“跳跃”行为。



UPDATE: Online demo to show behaviour

更新:在线演示以显示行为

I've uploaded an html demo page that shows the behaviour I'm complaining about: http://www.wouldbebetter.com/demo/comment-demo.htm

我上传了一个 html 演示页面,显示了我抱怨的行为:http: //www.wouldbebetter.com/demo/comment-demo.htm

Just scroll to the bottom of the page and click any of the Replylinks to see the "jumpy" scrolling I'm referring to.

只需滚动到页面底部并单击任何Reply链接即可查看我所指的“跳跃式”滚动。

Note that this demo uses the scrollintoviewplugin of @Robert Koritnik's answer, but the behaviour is the same if I use, for instance, ScrollTo.

请注意,此演示使用scrollintoview@Robert Koritnik 的答案的插件,但如果我使用例如 ScrollTo,则行为是相同的。

采纳答案by Robert Koritnik

Yes there is a jQuery pluginthat scrolls to an element only if it's not within visible boundaries of the scrollable ancestor. I've written one does exactly what you require. And you will probably find it easier to use compared to scrollTo()since you only have to provide the element that you'd like to see.

是的,有一个 jQuery 插件,只有当元素不在可滚动祖先的可见边界内时,它才会滚动到元素。我写了一个完全符合你的要求。并且您可能会发现它更易于使用,scrollTo()因为您只需提供您想要查看的元素。

I could copy paste the code here, but since I add some additions from time to time it's better to link you to blog postwhere you'll find all the details related to programmatic scrolling and latest plugin code. Programmatic scrolling can be quite distracting to users and the whole user interface experience, so I suppose it will be an interesting read.

我可以将代码复制粘贴到此处,但由于我不时添加一些内容,因此最好将您链接到博客文章,在那里您可以找到与编程滚动和最新插件代码相关的所有详细信息。程序化滚动可能会让用户和整个用户界面体验分心,所以我想这将是一个有趣的阅读。

Usage

用法

Plugin is really simple to use:

插件使用起来非常简单:

$("#ElementToScrollIntoView").scrollintoview();

Plugin automatically finds nearest scrollable ancestor and scrolls it accordingly (if at all needed). There are some additional settings to this plugin you can use and this is how they look like:

插件会自动找到最近的可滚动祖先并相应地滚动它(如果需要的话)。您可以使用此插件的一些其他设置,它们如下所示:

scrollintoview: function (options) {
    /// <summary>Scrolls the first element in the set into view by scrolling its closest scrollable parent.</summary>
    /// <param name="options" type="Object">Additional options that can configure scrolling:
    ///        duration (default: "fast") - jQuery animation speed (can be a duration string or number of milliseconds)
    ///        direction (default: "both") - select possible scrollings ("vertical" or "y", "horizontal" or "x", "both")
    ///        complete (default: none) - a function to call when scrolling completes (called in context of the DOM element being scrolled)
    /// </param>
    /// <return type="jQuery">Returns the same jQuery set that this function was run on.</return>

I'm using this plugin on my Sharepoint 2010 site on pages where I present long tabular data. Whenever I add a new item (row) to this table I additionally scroll to this new record and highlight it, so users can see the new record immediately.

我在我的 Sharepoint 2010 网站上的页面上使用了这个插件,我在其中展示了长表格数据。每当我向该表添加新项目(行)时,我还会滚动到这条新记录并突出显示它,以便用户可以立即看到新记录。

Sharepoint was also the reason why I decided not to provide scrollable element manually but rather look for it programatically. Sharepoint uses admin costumizable master pages which means I don't know which element is going to be scrollable at runtime. But I do know which element I want to see. Hence this plugin. It's also rather simplified compared to scrollTo()plugin that supports various different scenarios. Most of the time developers tend to use only one (or a very limited number of them).

Sharepoint 也是我决定不手动提供可滚动元素而是以编程方式寻找它的原因。Sharepoint 使用管理员可定制的母版页,这意味着我不知道哪个元素将在运行时滚动。但我知道我想看到哪个元素。因此这个插件。与scrollTo()支持各种不同场景的插件相比,它也相当简化。大多数时候,开发人员倾向于只使用一个(或非常有限的数量)。

Additional observations

其他观察

Default link click processing prevention

默认链接点击处理预防

Using my plugins still makes it rather problematic, since there's some flickering when adding those reply boxes. The problem is that your link clicking actually executes. You should prevent this in order to make your page to work smooth:

使用我的插件仍然有问题,因为添加这些回复框时会有一些闪烁。问题是您的链接点击实际执行。您应该防止这种情况,以使您的页面顺利运行:

  1. either set click events on your links in one of these two ways:

    <a href="javascript:void AddReplyForm(44); return false;">Reply</a>
    

    or

    <a href="#" onclick="void AddReplyForm(44); return false;">Reply</a>
    
  2. a better way would be to run this on document ready:

    $(function() {
        $("a").click(function(evt) {
            evt.preventDefault();
        });
    });
    
  1. 通过以下两种方式之一在链接上设置点击事件:

    <a href="javascript:void AddReplyForm(44); return false;">Reply</a>
    

    或者

    <a href="#" onclick="void AddReplyForm(44); return false;">Reply</a>
    
  2. 更好的方法是在文档就绪时运行它:

    $(function() {
        $("a").click(function(evt) {
            evt.preventDefault();
        });
    });
    

The main idea is to prevent browser from processing link clicks. Because this makes the browser to look for in-page anchor and since it can't find one, it auto scrolls to the top. Then you tell it to scroll to your element.

主要思想是防止浏览器处理链接点击。因为这会使浏览器寻找页内锚点,并且由于找不到,它会自动滚动到顶部。然后你告诉它滚动到你的元素。

Duplicate IDs

重复的 ID

When you create reply form, you add new and new and new elements but they're all with the same ID. You should either avoid doing this or use some other means. You could remove the need for IDs altogether by providing the element to your BindClick()function. The main reply generating function could as well look like this (this function is written in a way that completely eliminates the need for element IDs):

创建回复表单时,您会添加新元素和新元素,但它们都具有相同的 ID。您应该避免这样做或使用其他方法。您可以通过为您的BindClick()函数提供元素来完全消除对 ID 的需求。主要的回复生成函数也可以是这样的(这个函数的编写方式完全不需要元素 ID):

function AddReplyForm(topCommentID)
{
    var el = $(addReplyForm).appendTo('#comment_' + topCommentID + ' .right');
    BindClick(el); // mind this !! you provide the element to remove
    el.scrollintoview();
}

回答by Magu

All modern Browsers support this. Visit: http://caniuse.com/#search=scrollIntoView

所有现代浏览器都支持这一点。访问:http: //caniuse.com/#search=scrollIntoView

function scrollIntoViewIfNeeded(target) {
    var rect = target.getBoundingClientRect();
    if (rect.bottom > window.innerHeight) {
        target.scrollIntoView(false);
    }
    if (rect.top < 0) {
        target.scrollIntoView();
    } 
}

Update

更新

The target has to be an Element. If you use jQuery call the function like this:

目标必须是一个元素。如果您使用 jQuery 调用函数,如下所示:

scrollIntoViewIfNeeded($(".target")[0]);

回答by iandisme

Had the same problem... after reviewing a few answers, here's what I came up with for doing this... without pulling down another plugin.

遇到了同样的问题......在查看了一些答案之后,这就是我想出的办法......没有拉下另一个插件。

function scrollIntoViewIfNeeded($target) {
    if ($target.position()) {
        if ($target.position().top < jQuery(window).scrollTop()){
            //scroll up
            $('html,body').animate({scrollTop: $target.position().top});
        }
        else if ($target.position().top + $target.height() >
            $(window).scrollTop() + (
                window.innerHeight || document.documentElement.clientHeight
            )) {
            //scroll down
            $('html,body').animate({scrollTop: $target.position().top -
                (window.innerHeight || document.documentElement.clientHeight)
                    + $target.height() + 15}
            );
        }
    }
}

The "15" on the last line is just extra padding - you might need to adjust it, or add it to the scroll up line.

最后一行的“15”只是额外的填充 - 您可能需要调整它,或将其添加到向上滚动行。

EDIT: changed window.innerHeightto (window.innerHeight || document.documentElement.clientHeight)for IE < 8 support

编辑:改变window.innerHeight(window.innerHeight || document.documentElement.clientHeight)为IE <8支持

回答by kofifus

to make sure elem is in view inside a container:

确保 elem 在容器内可见:

let rectElem = elem.getBoundingClientRect(), rectContainer=container.getBoundingClientRect();
if (rectElem.bottom > rectContainer.bottom) elem.scrollIntoView(false);
if (rectElem.top < rectContainer.top) elem.scrollIntoView();

回答by bmode

I modified the answer from @iandisme a bit and wrapped it up as a tiny jquery plugin:

我稍微修改了@iandisme 的答案,并将其包装为一个很小的 ​​jquery 插件:

(function ($) {
'use strict';

$.fn.scrollToSimple = function ($target) {
    var $container = this.first();      // Only scrolls the first matched container

    var pos = $target.position(), height = $target.outerHeight();
    var containerScrollTop = $container.scrollTop(), containerHeight = $container.height();
    var top = pos.top + containerScrollTop;     // position.top is relative to the scrollTop of the containing element

    var paddingPx = containerHeight * 0.15;      // padding keeps the target from being butted up against the top / bottom of the container after scroll

    if (top < containerScrollTop) {     // scroll up                
        $container.scrollTop(top - paddingPx);
    }
    else if (top + height > containerScrollTop + containerHeight) {     // scroll down
        $container.scrollTop(top + height - containerHeight + paddingPx);
    }
};
})(jQuery);

I removed the calls to .animate since I was looking for instant scrolling. I also added the ability to scroll any (scrollable) container, rather than just the window. Example usage:

我删除了对 .animate 的调用,因为我正在寻找即时滚动。我还添加了滚动任何(可滚动)容器的功能,而不仅仅是窗口。用法示例:

// scroll the window so #target  is visible
$(window).scrollToSimple( $("#target") );

// scroll the scrollable element #container so that #target is visible
$("#container").scrollToSimple( $("#target") );

回答by Grant Miller

Element.scrollIntoViewIfNeeded()

Element.scrollIntoViewIfNeeded()

According to MDN Web Docs:

根据MDN 网络文档

The Element.scrollIntoViewIfNeeded()method scrolls the current element into the visible area of the browser window if it's not already within the visible area of the browser window. If the element is already within the visible area of the browser window, then no scrolling takes place. This method is a proprietary variation of the standard Element.scrollIntoView()method.

如果Element.scrollIntoViewIfNeeded()当前元素不在浏览器窗口的可见区域内,该方法会将当前元素滚动到浏览器窗口的可见区域。如果元素已经在浏览器窗口的可见区域内,则不会发生滚动。该方法是标准Element.scrollIntoView()方法的专有变体。

Example (with jQuery):

示例(使用 jQuery):

$('#example')[0].scrollIntoViewIfNeeded();

Note:This feature is non-standard and is not on a standards track, so use caution before using this in production. See Can I use...for browser support.

注意:此功能是非标准的,不在标准轨道上,因此在生产中使用它之前要小心。有关浏览器支持,请参阅Can I use...。

回答by Etherman

I use the answer from kofifus (https://stackoverflow.com/a/43010437/1075062), except in many cases I don't know what the container is so I use answers from (Find first scrollable parent) to find that out. I use jQuery UI so I have the .scrollParent() method available to me (you can find a port of it in the linked question if you need it). I also use the proprietary scrollIntoViewIfNeeded if present, which is in many modern browsers, so the custom code currently only is needed for FireFox and Opera Mini (and old browsers) (https://caniuse.com/#feat=scrollintoviewifneeded).

我使用 kofifus 的答案(https://stackoverflow.com/a/43010437/1075062),除了在许多情况下我不知道容器是什么,所以我使用(找到第一个可滚动父级)的答案来找出答案. 我使用 jQuery UI,所以我可以使用 .scrollParent() 方法(如果需要,可以在链接的问题中找到它的端口)。我还使用专有的 scrollIntoViewIfNeeded(如果存在),它在许多现代浏览器中都有,所以目前只有 FireFox 和 Opera Mini(以及旧浏览器)需要自定义代码(https://caniuse.com/#feat=scrollintoviewifneeded)。

(code is TypeScript)

(代码是 TypeScript)

/**
 * Scroll the element into view if not already visible.
 *
 * https://caniuse.com/#feat=scrollintoviewifneeded
 * https://stackoverflow.com/questions/5685589/scroll-to-element-only-if-not-in-view-jquery
 * https://stackoverflow.com/questions/35939886/find-first-scrollable-parent
 */
public static ScrollIntoViewIfNeeded(element: Element): void
{
    if (element)
    {
        // Proprietary method, available in many modern browsers
        if ((<any>element).scrollIntoViewIfNeeded)
        {
            (<any>element).scrollIntoViewIfNeeded();
        }
        else
        {
            let $element = $(element);

            // jQuery UI scrollParent method available?
            if ($element.scrollParent)
            {
                let $parent = $(element).scrollParent();
                let rectElem = element.getBoundingClientRect();
                let rectContainer = $parent[0].getBoundingClientRect();

                if (rectElem.bottom > rectContainer.bottom || rectElem.top < rectContainer.top)
                {
                    element.scrollIntoView();
                }
            }
            else if (element.scrollIntoView)
            {
                element.scrollIntoView();
            }
        }
    }
}

回答by msmafra

I don't know if I understood what you want but see if this is it, close to or if I'm totally lost:

我不知道我是否理解你想要的,但看看是不是这样,接近或者我完全迷失了:

<!DOCTYPE html>
<html>
    <head>
        <title>Scroll To Reply</title>
        <meta charset="utf-8" />
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                var $contextarea = $('#contextform textarea');
                $('a.reply').live('click',function(){
                    $(this).closest('p').css({'margin-top':'300px;'});
                    $('#contextform').appendTo($(this).closest('p'));
                    $('#contextform').slideDown(1000);//.css({'display':'block'});
                    $(this).closest('p').attr('id','scrolltome');
                    $('html,body').animate({slideDown: $('#scrolltome').offset().top}, 2000);
                });
                $('.sendreply').live('click',function(){
                    if($contextarea.val() == null || $contextarea.val() == '') {
                        alert('textarea is empty!');
                    } else {
                        $('#contextform').slideUp(800);
                    }
                });

                //                $('button').click(function() {
                //                    $('html,body').animate({scrollTop: $('#body').offset().top}, 2000);//scrolls to the top
                //                });

            });
        </script>
        <style type="text/css">
            body{
                font-size:25px;
                font-family: 'Arimo', Arial, sans-serif;
            }
            #contextform {
                display:none;
                width:500px;
                height: 150px;
                background: #0489B7;
                padding: 5px
            }
            #contextform textarea {
                width: 490px;
                height: 90px;
            }
        </style>
    </head>
    <body id="body">
        <h1>Scroll to reply</h1>
        <div id="contextform">
            <form method="post" action="">
                <textarea id="textarea"></textarea>
                <button type="button" class="sendreply">Send Reply</button>
            </form>
            <a name="myAnchor" id="myAnchor">anchor</a>
        </div>
        <ol>
            <?php for ($i = 0; $i < 20; $i++) { ?>
                <li><p>The quick brown fox jumps over the lazy dog
                        <a href="#scrolltome" class="reply">Reply</a>
                    </p></li>
            <?php } ?>
        </ol>
    </body>
</html>

回答by dallin

Every answer here either seemed outdated and no longer working with modern versions of jQuery (probably due to changes in the position() and offset() functions for example) or too limited to work in the circumstances I needed them for. For example, none of the above answers seemed to work if your code was in an iframe.

这里的每个答案要么似乎已经过时,不再适用于现代版本的 jQuery(例如,可能是由于 position() 和 offset() 函数的变化),或者太有限而无法在我需要它们的情况下工作。例如,如果您的代码在 iframe 中,则上述答案似乎都不起作用。

One of the biggest things I noticed was all of them just used the normal height of the container object, which worked fine as long as the entire container object was visible in the window, but when your container object was the html object itself and the height extended far below what was shown, the scroll down portion of the code no longer worked. Instead, the algorithm needs to use the object's visible height on the screen for it to work properly (see Get the visible height of a div with jQuery).

我注意到的最重要的事情之一是它们都只使用容器对象的正常高度,只要整个容器对象在窗口中可见,它就可以正常工作,但是当您的容器对象是 html 对象本身和高度时远远低于显示的内容,代码的向下滚动部分不再有效。相反,该算法需要使用对象在屏幕上的可见高度才能使其正常工作(请参阅使用 jQuery 获取 div 的可见高度)。

I ended up writing my own solution that seems much more robust and works in more circumstances:

我最终编写了自己的解决方案,该解决方案看起来更加健壮并且适用于更多情况:

function scrollIntoViewIfNeeded($target, options) {

    var options = options ? options : {},
    $win = $($target[0].ownerDocument.defaultView), //get the window object of the $target, don't use "window" because the element could possibly be in a different iframe than the one calling the function
    $container = options.$container ? options.$container : $win,        
    padding = options.padding ? options.padding : 20,
    elemTop = $target.offset().top,
    elemHeight = $target.outerHeight(),
    containerTop = $container.scrollTop(),
    //Everything past this point is used only to get the container's visible height, which is needed to do this accurately
    containerHeight = $container.outerHeight(),
    winTop = $win.scrollTop(),
    winBot = winTop + $win.height(),
    containerVisibleTop = containerTop < winTop ? winTop : containerTop,
    containerVisibleBottom = containerTop + containerHeight > winBot ? winBot : containerTop + containerHeight,
    containerVisibleHeight = containerVisibleBottom - containerVisibleTop;

    if (elemTop < containerTop) {
        //scroll up
        if (options.instant) {
            $container.scrollTop(elemTop - padding);
        } else {
            $container.animate({scrollTop: elemTop - padding}, options.animationOptions);
        }
    } else if (elemTop + elemHeight > containerTop + containerVisibleHeight) {
        //scroll down
        if (options.instant) {
            $container.scrollTop(elemTop + elemHeight - containerVisibleHeight + padding);
        } else {
            $container.animate({scrollTop: elemTop + elemHeight - containerVisibleHeight + padding}, options.animationOptions);
        }
    }
}

$targetis a jQuery object containing the object you wish to scroll into view if needed.

$target是一个 jQuery 对象,其中包含您希望在需要时滚动到视图中的对象。

options(optional) can contain the following options passed in an object:

options(可选)可以包含在对象中传递的以下选项:

options.$container- a jQuery object pointing to the containing element of $target (in other words, the element in the dom with the scrollbars). Defaults to the window that contains the $target element and is smart enough to select an iframe window. Remember to include the $ in the property name.

options.$container- 一个 jQuery 对象,指向包含 $target 的元素(换句话说,dom 中带有滚动条的元素)。默认为包含 $target 元素并且足够智能以选择 iframe 窗口的窗口。请记住在属性名称中包含 $。

options.padding- the padding in pixels to add above or below the object when it is scrolled into view. This way it is not right against the edge of the window. Defaults to 20.

options.padding- 当对象滚动到视图中时,要在对象上方或下方添加的填充(以像素为单位)。这样它就不会紧贴窗户的边缘。默认为 20。

options.instant- if set to true, jQuery animate will not be used and the scroll will instantly pop to the correct location. Defaults to false.

options.instant- 如果设置为 true,将不会使用 jQuery 动画并且滚动会立即弹出到正确的位置。默认为假。

options.animationOptions- any jQuery options you wish to pass to the jQuery animate function (see http://api.jquery.com/animate/). With this, you can change the duration of the animation or have a callback function executed when the scrolling is complete. This only works if options.instantis set to false. If you need to have an instant animation but with a callback, set options.animationOptions.duration = 0instead of using options.instant = true.

options.animationOptions- 您希望传递给 jQuery animate 函数的任何 jQuery 选项(请参阅http://api.jquery.com/animate/)。有了这个,您可以更改动画的持续时间或在滚动完成时执行回调函数。这仅在options.instant设置为 false 时有效。如果您需要即时动画但带有回调,请设置options.animationOptions.duration = 0而不是使用options.instant = true.

回答by Lawrence Dol

JQuery is not required for this.

为此不需要 JQuery。

This function just shows the specified element:

这个函数只显示指定的元素:

function scrollIntoView(elm) {
    if(elm) {
        let bnd=elm.getBoundingClientRect();
        if     (bnd.top<0                    ) { elm.scrollIntoView(true );      }
        else if(bnd.bottom>window.innerHeight) { elm.scrollIntoView(bnd.top<=0); }
        }
    return elm;
    }

The following more capable function allows a container of the desired element to be scrolled into view, also providing the ability to easily ensure that the entire container is made visible so that half-occluded visuals are avoided.

以下功能更强大的功能允许将所需元素的容器滚动到视图中,还提供了轻松确保整个容器可见的能力,从而避免了半遮挡的视觉效果。

/**
  * Scroll the specified element into view, optionally first searching for a specific container and
  * first making that visible. This function does it's best to scroll the entire container into view
  * but ultimately ensures that as much of the element as fits in the viewport will be visible.
  *
  * #### Arguments:
  *
  *     elm (DOMElement)    The element to make visible.
  *     contag (string)     Optional name of a container tag. Ignored if blank/null/omitted.
  *     conprp (string)     Optional name of a container property to also match. Ignored if blank/null/omitted.
  *     conval (string)     Optional value of the container property. Ignored if `conprp` is not supplied; defaults to "" if omitted.
  */
function scrollIntoView(elm,contag,conprp,conval) {
    if(elm) {
        if(contag || conprp) {
            let con;
            if(conval==null) { conval=""; }
            for(con=elm; con!=null && con.tagName!="BODY"; con=con.parentNode) {
                if((!contag || contag==con.tagName) && (!conprp || con[conprp]==conval)) {
                    break;                                                                          // matched container tag and property
                    }
                }
            if(con) { scrollIntoView(con); }
            }

        let bnd=elm.getBoundingClientRect();

        if     (bnd.top<0                    ) { elm.scrollIntoView(true );      }
        else if(bnd.bottom>window.innerHeight) { elm.scrollIntoView(bnd.top<=0); }
        }
    return elm;
    }

This makes it easy to, for example, show this when scrolling up:

例如,这可以很容易地在向上滚动时显示:

enter image description here

在此处输入图片说明

instead of this:

而不是这个:

enter image description here

在此处输入图片说明