Javascript scrollIntoView() 中间对齐?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8922107/
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-24 08:05:54  来源:igfitidea点击:

Javascript scrollIntoView() middle alignment?

javascriptjs-scrollintoview

提问by DHRUV BANSAL

Javascript .scrollIntoView(boolean)provide only two alignment option.

Javascript.scrollIntoView(boolean)只提供两个对齐选项。

  1. top
  2. bottom
  1. 最佳
  2. 底部

What if I want to scroll the view such that. I want to bring particular element somewhere in middle of the page?

如果我想滚动视图怎么办。我想将特定元素放在页面中间的某个地方?

采纳答案by ThinkingStiff

Use window.scrollTo()for this. Get the top of the element you want to move to, and subtract one half the window height.

window.scrollTo()为此使用。获取要移动到的元素的顶部,然后减去窗口高度的一半。

Demo: http://jsfiddle.net/ThinkingStiff/MJ69d/

演示:http: //jsfiddle.net/ThinkingStiff/MJ69d/

Element.prototype.documentOffsetTop = function () {
    return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop() : 0 );
};

var top = document.getElementById( 'middle' ).documentOffsetTop() - ( window.innerHeight / 2 );
window.scrollTo( 0, top );

回答by Rohan Orton

It is possible to use getBoundingClientRect()to get all the information you need to achieve this. For example, you could do something like this:

可以使用它getBoundingClientRect()来获取实现此目标所需的所有信息。例如,您可以执行以下操作:

const element = document.getElementById('middle');
const elementRect = element.getBoundingClientRect();
const absoluteElementTop = elementRect.top + window.pageYOffset;
const middle = absoluteElementTop - (window.innerHeight / 2);
window.scrollTo(0, middle);

Demo: http://jsfiddle.net/cxe73c22/

演示:http: //jsfiddle.net/cxe73c22/

This solution is more efficient than walking up parent chain, as in the accepted answer, and doesn't involve polluting the global scope by extending prototype (generally considered bad practice in javascript).

这个解决方案比在接受的答案中走父链更有效,并且不涉及通过扩展原型来污染全局范围(在 javascript 中通常被认为是不好的做法)。

The getBoundingClientRect()method is supported in all modern browser.

getBoundingClientRect()所有现代浏览器都支持该方法。

回答by hakuna

try this :

尝试这个 :

 document.getElementById('myID').scrollIntoView({
            behavior: 'auto',
            block: 'center',
            inline: 'center'
        });

refer here for more information and options : https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

有关更多信息和选项,请参阅此处:https: //developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

回答by fred727

You can do it in two steps :

您可以分两步完成:

myElement.scrollIntoView(true);
var viewportH = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
window.scrollBy(0, -viewportH/2); // Adjust scrolling with a negative value here

You can add the height of the element if you want to center it globaly, and not center its top :

如果要全局居中而不是顶部居中,可以添加元素的高度:

myElement.scrollIntoView(true);
var viewportH = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
window.scrollBy(0, (myElement.getBoundingClientRect().height-viewportH)/2);

回答by SergiP

With JQuery I use this:

使用 JQuery 我使用这个:

function scrollToMiddle(id) {

    var elem_position = $(id).offset().top;
    var window_height = $(window).height();
    var y = elem_position - window_height/2;

    window.scrollTo(0,y);

}

Example:

例子:

<div id="elemento1">Contenido</div>

<script>
    scrollToMiddle("#elemento1");
</script>

回答by Yash

Improving the answer of @Rohan Ortonto work for vertical and horizontal scroll.

改进@Rohan Orton对垂直和水平滚动工作的答案。

The Element.getBoundingClientRect()method returns the size of an element and its position relative to the viewport.

所述Element.getBoundingClientRect()方法返回的元素的相对于视其位置和大小。

var ele = $x("//a[.='Ask Question']");
console.log( ele );

scrollIntoView( ele[0] );

function scrollIntoView( element ) {
    var innerHeight_Half = (window.innerHeight >> 1); // Int value
                        // = (window.innerHeight / 2); // Float value
    console.log('innerHeight_Half : '+ innerHeight_Half);

    var elementRect = element.getBoundingClientRect();

    window.scrollBy( (elementRect.left >> 1), elementRect.top - innerHeight_Half);
}

Using Bitwise operatorright shift to get int value after dividing.

Bitwise operator除法后使用右移得到int值。

console.log( 25 / 2 ); // 12.5
console.log( 25 >> 1 ); // 12

回答by dube

None of the solutions on this page work when an container other than the window/document is scrolled. The getBoundingClientRectapproach fails with absolute positioned elements.

当滚动窗口/文档以外的容器时,此页面上的所有解决方案都不起作用。该getBoundingClientRect方法因绝对定位元素而失败。

In that case we need to determine the scrollable parent first and scroll it instead of the window. Here is a solution that works in all current browser versions and should even work with IE8 and friends. The trick is to scroll the element to the top of the container, so that we know exactly where it is, and then subtract half of the screen's height.

在这种情况下,我们需要首先确定可滚动的父级并滚动它而不是窗口。这是一个适用于所有当前浏览器版本的解决方案,甚至应该适用于 IE8 和朋友。诀窍是将元素滚动到容器的顶部,以便我们确切地知道它在哪里,然后减去屏幕高度的一半。

function getScrollParent(element, includeHidden, documentObj) {
    let style = getComputedStyle(element);
    const excludeStaticParent = style.position === 'absolute';
    const overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/;

    if (style.position === 'fixed') {
        return documentObj.body;
    }
    let parent = element.parentElement;
    while (parent) {
        style = getComputedStyle(parent);
        if (excludeStaticParent && style.position === 'static') {
            continue;
        }
        if (overflowRegex.test(style.overflow + style.overflowY + style.overflowX)) {
            return parent;
        }
        parent = parent.parentElement;
    }

    return documentObj.body;
}

function scrollIntoViewCentered(element, windowObj = window, documentObj = document) {
    const parentElement = getScrollParent(element, false, documentObj);
    const viewportHeight = windowObj.innerHeight || 0;

    element.scrollIntoView(true);
    parentElement.scrollTop = parentElement.scrollTop - viewportHeight / 2;

    // some browsers (like FireFox) sometimes bounce back after scrolling
    // re-apply before the user notices.
    window.setTimeout(() => {
        element.scrollIntoView(true);
        parentElement.scrollTop = parentElement.scrollTop - viewportHeight / 2;
    }, 0);
}

回答by Matt Wyndham

Scrolling to the middle of an element works well if its parent element has the css: overflow: scroll;

如果其父元素具有 css,则滚动到元素的中间效果很好: overflow: scroll;

If it's a vertical list, you can use document.getElementById("id").scrollIntoView({block: "center"});and it will scroll your selected element to the vertical middle of the parent element.

如果它是一个垂直列表,您可以使用document.getElementById("id").scrollIntoView({block: "center"});它,它会将您选择的元素滚动到父元素的垂直中间。

Cheers to Gregory R. and Hakuna for their good answers.

为 Gregory R. 和 Hakuna 的好答案干杯。

Further Reading:

进一步阅读:

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

https://developer.mozilla.org/en-US/docs/Web/CSS/overflow

https://developer.mozilla.org/en-US/docs/Web/CSS/overflow

回答by Gregory R.

document.getElementById("id").scrollIntoView({block: "center"});