我有一个滚动的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 -平滑滚动到元素中的元素

var box = document.querySelector('.box'), targetElm = document.querySelector('.boxChild'); // <-- Scroll to here within ".box" document.querySelector('button').addEventListener('click', function(){ scrollToElm( box, targetElm , 600 ); }); ///////////// function scrollToElm(container, elm, duration){ var pos = getRelativePos(elm); scrollTo( container, pos.top , 2); // duration in seconds } function getRelativePos(elm){ var pPos = elm.parentNode.getBoundingClientRect(), // parent pos cPos = elm.getBoundingClientRect(), // target pos pos = {}; pos.top = cPos.top - pPos.top + elm.parentNode.scrollTop, pos.right = cPos.right - pPos.right, pos.bottom = cPos.bottom - pPos.bottom, pos.left = cPos.left - pPos.left; return pos; } function scrollTo(element, to, duration, onDone) { var start = element.scrollTop, change = to - start, startTime = performance.now(), val, now, elapsed, t; function animateScroll(){ now = performance.now(); elapsed = (now - startTime)/1000; t = (elapsed/duration); element.scrollTop = start + change * easeInOutQuad(t); if( t < 1 ) window.requestAnimationFrame(animateScroll); else onDone && onDone(); }; animateScroll(); } function easeInOutQuad(t){ return t<.5 ? 2*t*t : -1+(4-2*t)*t }; .box{ width:80%; border:2px dashed; height:180px; overflow:auto; } .boxChild{ margin:600px 0 300px; width: 40px; height:40px; background:green; } <button>Scroll to element</button> <div class='box'> <div class='boxChild'></div> </div>

方法2 -使用Element.scrollIntoView:

请注意,浏览器支持并不适合这个版本

var targetElm = document.querySelector('.boxChild'), // reference to scroll target button = document.querySelector('button'); // button that triggers the scroll // bind "click" event to a button button.addEventListener('click', function(){ targetElm.scrollIntoView() }) .box { width: 80%; border: 2px dashed; height: 180px; overflow: auto; scroll-behavior: smooth; /* <-- for smooth scroll */ } .boxChild { margin: 600px 0 300px; width: 40px; height: 40px; background: green; } <button>Scroll to element</button> <div class='box'> <div class='boxChild'></div> </div>

方法3 -使用CSS滚动行为:

.box { 宽度:80%; 边框:2px虚线; 身高:180 px; overflow-y:滚动; scroll-behavior:光滑;/* <——*/ } # boxChild { Margin: 600px 0 300px; 宽度:40像素; 高度:40像素; 背景:绿色; } <a href='#boxChild'>滚动到元素</a> < div class =“盒子”> < div id =“boxChild”> < / div > < / div >

原生JS,跨浏览器,平滑滚动(更新2020)

设置ScrollTop确实可以得到想要的结果,但是滚动非常突然。使用jquery来平滑滚动不是一个选择。因此,这里有一种支持所有主流浏览器的本机方式来完成工作。参比犬

// get the "Div" inside which you wish to scroll (i.e. the container element)
const El = document.getElementById('xyz');

// Lets say you wish to scroll by 100px, 
El.scrollTo({top: 100, behavior: 'smooth'});

// If you wish to scroll until the end of the container
El.scrollTo({top: El.scrollHeight, behavior: 'smooth'});

就是这样!


And here's a working snippet for the doubtful - document.getElementById('btn').addEventListener('click', e => { e.preventDefault(); // smooth scroll document.getElementById('container').scrollTo({top: 175, behavior: 'smooth'}); }); /* just some styling for you to ignore */ .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; } <!-- Dummy html to be ignored --> <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">goose</button>

更新:正如你在评论中看到的,IE11似乎不支持Element.scrollTo()。所以如果你不关心IE11(你真的不应该,微软将在2022年6月退休IE11),请在你所有的项目中使用它。注意,支持Edge!所以你并没有真正离开你的Edge/Windows用户;)

参考

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

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

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);
    }
};

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

/**
 * 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;
    }
};

下面是一些用法的例子:

// 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);

另一个使用jQuery和动画的例子。

var container = $('#container');
var element = $('#element');

container.animate({
    scrollTop: container.scrollTop = container.scrollTop() + element.offset().top - container.offset().top
}, {
    duration: 1000,
    specialEasing: {
        width: 'linear',
        height: 'easeOutBounce'
    },
    complete: function (e) {
        console.log("animation completed");
    }
});