我有一个滚动的div,我想有一个事件,当我点击它,它将迫使这个div滚动查看里面的一个元素。 我这样写它的JavasSript:

document.getElementById(chr).scrollIntoView(true);

但这在滚动div本身的同时滚动整个页面。 如何解决这个问题?

我想这样说: MyContainerDiv.getElementById(杆).scrollIntoView(真正的);


当前回答

有两个事实:

1) safari不支持scrollIntoView组件。

2) JS框架jQuery可以做这样的工作:

parent = 'some parent div has css position==="fixed"' || 'html, body';

$(parent).animate({scrollTop: $(child).offset().top}, duration)

其他回答

有两个事实:

1) safari不支持scrollIntoView组件。

2) JS框架jQuery可以做这样的工作:

parent = 'some parent div has css position==="fixed"' || 'html, body';

$(parent).animate({scrollTop: $(child).offset().top}, duration)

只有在需要的时候,你才能使用scrollIfNeeded函数将一个元素滚动到div的视图中:

function scrollIfNeeded(element, container) { if (element.offsetTop < container.scrollTop) { container.scrollTop = element.offsetTop; } else { const offsetBottom = element.offsetTop + element.offsetHeight; const scrollBottom = container.scrollTop + container.offsetHeight; if (offsetBottom > scrollBottom) { container.scrollTop = offsetBottom - container.offsetHeight; } } } document.getElementById('btn').addEventListener('click', ev => { ev.preventDefault(); scrollIfNeeded(document.getElementById('goose'), document.getElementById('container')); }); .scrollContainer { overflow-y: auto; max-height: 100px; position: relative; border: 1px solid red; width: 120px; } body { padding: 10px; } .box { margin: 5px; background-color: yellow; height: 25px; display: flex; align-items: center; justify-content: center; } #goose { background-color: lime; } <div id="container" class="scrollContainer"> <div class="box">duck</div> <div class="box">duck</div> <div class="box">duck</div> <div class="box">duck</div> <div class="box">duck</div> <div class="box">duck</div> <div class="box">duck</div> <div class="box">duck</div> <div id="goose" class="box">goose</div> <div class="box">duck</div> <div class="box">duck</div> <div class="box">duck</div> <div class="box">duck</div> </div> <button id="btn">scroll to goose</button>

我们可以在不使用JQuery和其他库的情况下解决这个问题。

为此,我编写了以下代码:

你有相似的结构,>

<div class="parent">
  <div class="child-one">

  </div>
  <div class="child-two">

  </div>
</div>

JS:

scrollToElement() {
  var parentElement = document.querySelector('.parent');
  var childElement = document.querySelector('.child-two');

  parentElement.scrollTop = childElement.offsetTop - parentElement.offsetTop;
}

我们可以很容易地重写这个方法,以参数的形式传递父和子

这就是我最终得到的

/** Set parent scroll to show element
 * @param element {object} The HTML object to show
 * @param parent {object} The HTML object where the element is shown  */
var scrollToView = function(element, parent) {
    //Algorithm: Accumulate the height of the previous elements and add half the height of the parent
    var offsetAccumulator = 0;
    parent = $(parent);
    parent.children().each(function() {
        if(this == element) {
            return false; //brake each loop
        }
        offsetAccumulator += $(this).innerHeight();
    });
    parent.scrollTop(offsetAccumulator - parent.innerHeight()/2);
}

我需要滚动页面上的动态加载元素,所以我的解决方案有点复杂。

这将适用于静态元素,这些静态元素不是惰性加载数据,也不是动态加载数据。

const smoothScrollElement = async (selector: string, scrollBy = 12, prevCurrPos = 0) => {
    const wait = (timeout: number) => new Promise(resolve => setTimeout(resolve, timeout));
    const el = document.querySelector(selector) as HTMLElement;
    let positionToScrollTo = el.scrollHeight;
    let currentPosition = Math.floor(el.scrollTop) || 0;
    let pageYOffset = (el.clientHeight + currentPosition);
    if (positionToScrollTo == pageYOffset) {
        await wait(1000);
    }
    if ((prevCurrPos > 0 && currentPosition <= prevCurrPos) !== true) {
        setTimeout(async () => {
            el.scrollBy(0, scrollBy);
            await smoothScrollElement(selector, scrollBy, currentPosition);
        }, scrollBy);
    }
};