使用纯 Javascript 滚动到可滚动 DIV 内的元素

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

Scrolling to a element inside a scrollable DIV with pure Javascript

javascript

提问by bluefog

I have a div that has overflow: scrolland I have some elements inside the DIV that are hidden. On click of a button on the page, I want to make the DIV scroll to a particular element inside the DIV.

我有一个 divoverflow: scroll并且我在 DIV 中有一些隐藏的元素。单击页面上的按钮时,我想让 DIV 滚动到 DIV 内的特定元素。

How do I achieve this?

我如何实现这一目标?

回答by bluefog

You need to read the offsetTopproperty of the div you need to scroll to and then set that offset to the scrollTopproperty of the container div. Bind this function the event you want to :

您需要读取offsetTop需要滚动到的 div的属性,然后将该偏移设置scrollTop为 container的属性div。将此函数绑定到您想要的事件:

function scrollToElementD(){
    var topPos = document.getElementById('inner-element').offsetTop;
    document.getElementById('container').scrollTop = topPos-10;
}
div {
    height: 200px;
    width: 100px;
    border: 1px solid black;
    overflow: auto;
}

p {
    height: 80px;
    background: blue;
}
#inner-element {
    background: red;
}
<div id="container"><p>A</p><p>B</p><p>C</p><p id="inner-element">D</p><p>E</p><p>F</p></div>
<button onclick="scrollToElementD()">SCROLL TO D</button>

function scrollToElementD(){
  var topPos = document.getElementById('inner-element').offsetTop;
  document.getElementById('container').scrollTop = topPos-10;
}

Fiddle : http://jsfiddle.net/p3kar5bb/322/(courtesy @rofrischmann)

小提琴:http: //jsfiddle.net/p3kar5bb/322/(礼貌@rofrischmann)

回答by Jay Cam

Just improved it by setting a smooth auto scrolling inside a list contained in a div

只是通过在 div 中包含的列表中设置平滑自动滚动来改进它

https://codepen.io/rebosante/pen/eENYBv

https://codepen.io/rebosante/pen/eENYBv

var topPos = elem.offsetTop

document.getElementById('mybutton').onclick = function () {
   console.log('click')
  scrollTo(document.getElementById('container'), topPos-10, 600);   
}

function scrollTo(element, to, duration) {
    var start = element.scrollTop,
        change = to - start,
        currentTime = 0,
        increment = 20;

    var animateScroll = function(){        
        currentTime += increment;
        var val = Math.easeInOutQuad(currentTime, start, change, duration);
        element.scrollTop = val;
        if(currentTime < duration) {
            setTimeout(animateScroll, increment);
        }
    };
    animateScroll();
}

//t = current time
//b = start value
//c = change in value
//d = duration
Math.easeInOutQuad = function (t, b, c, d) {
    t /= d/2;
    if (t < 1) return c/2*t*t + b;
    t--;
    return -c/2 * (t*(t-2) - 1) + b;
};

I guess it may help someone :)

我想它可能会帮助某人:)

回答by NoBrainer

Here's a simple pure JavaScript solution that works for a target Number (value for scrollTop), target DOM element, or some special String cases:

这是一个简单的纯 JavaScript 解决方案,适用于目标 Number(值scrollTop)、目标 DOM 元素或一些特殊的 String 情况:

/**
 * target - target to scroll to (DOM element, scrollTop Number, 'top', or 'bottom'
 * containerEl - DOM element for the container with scrollbars
 */
var scrollToTarget = function(target, containerEl) {
    // Moved up here for readability:
    var isElement = target && target.nodeType === 1,
        isNumber = Object.prototype.toString.call(target) === '[object Number]';

    if (isElement) {
        containerEl.scrollTop = target.offsetTop;
    } else if (isNumber) {
        containerEl.scrollTop = target;
    } else if (target === 'bottom') {
        containerEl.scrollTop = containerEl.scrollHeight - containerEl.offsetHeight;
    } else if (target === 'top') {
        containerEl.scrollTop = 0;
    }
};

And here are some examples of usage:

以下是一些用法示例:

// Scroll to the top
var scrollableDiv = document.getElementById('scrollable_div');
scrollToTarget('top', scrollableDiv);

or

或者

// Scroll to 200px from the top
var scrollableDiv = document.getElementById('scrollable_div');
scrollToTarget(200, scrollableDiv);

or

或者

// Scroll to targetElement
var scrollableDiv = document.getElementById('scrollable_div');
var targetElement= document.getElementById('target_element');
scrollToTarget(targetElement, scrollableDiv);