简体   繁体   English

使用javascript自动滚动到范围的底部

[英]Scrolling to the bottom of a span automatically with javascript

I have a span defined, to which I am occasionally adding text and I am trying to get it to scroll to the bottom of the "box" but without success. 我有一个span定义,我偶尔会添加文本,我试图让它滚动到“框”的底部,但没有成功。

I have the span defined as: 我将范围定义为:

    <tr>
    <td style="height:130px; border: 1px solid black;">
    <div class="scrollable">
    <span id="infoWindow"></span>
    </div>
    </td>
    </tr>

With

div.scrollable 
{
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    overflow: auto;
}

And I am adding to it as follows: 我正在添加如下:

document.getElementById("infoWindow").innerHTML+="Just some blurb<hr>";



    var objDiv = document.getElementById("infoWindow");

I have tried two different approaches: 我尝试了两种不同的方法:

    objDiv.scrollTop = objDiv.scrollHeight - objDiv.clientHeight;

and

    objDiv.scrollTop = objDiv.scrollHeight; 

But neither work. 但是没有工作。 What am I doing wrong? 我究竟做错了什么? Many thanks! 非常感谢!

refer this https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop 请参阅此https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop

scrolling is applicable only to scrollable elements 滚动仅适用于可滚动元素

 var i= 0; while(i<10){ document.getElementById("infoWindow").innerHTML+="Just some blurb<hr>"; i++; } //get the total height of your element var bottomPosition = document.getElementById("infoWindow").offsetHeight; //set scroll of container element document.querySelector(".scrollable").scrollTop = bottomPosition; 
 div.scrollable { width: 100%; height: 100%; margin: 0; padding: 0; overflow: auto; } /* height is no defined for inline-elements so make span inline-block or block*/ #infoWindow{ display:inline-block; } 
 <table> <tr> <td style="height:130px; border: 1px solid black;"> <div class="scrollable"> <!-- added style for span element --> <span id="infoWindow"></span> </div> </td> </tr> </table> 

scrollHeight and clientHeight are properties which are calculated when DOM has been fully painted. scrollHeightclientHeight是在完全绘制DOM时计算的属性。 You should subscribe to event DOMContentLoaded to be sure the calculations are done. 您应该订阅事件DOMContentLoaded以确保计算完成。

There is a function scrollIntoView which you can use on any element which does exactly the name suggests. 有一个函数scrollIntoView ,你可以使用任何完全符合名称的元素。 MDN - scrollIntoView . MDN - scrollIntoView You can also define some options for scrolling like smoothness and position where to scroll exactly on element. 您还可以定义一些滚动选项,如平滑度和位置,以准确滚动元素。

Here is an example I wrote to test this. 这是我写的一个例子来测试这个。

Keep in mind that scrollIntoView triggered by code example will impact SO scroll behavior. 请记住,代码示例触发的scrollIntoView将影响SO滚动行为。

 const paragraphs = ['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliter enim nosmet ipsos nosse non possumus. Sin dicit obscurari quaedam nec apparere, quia valde parva sint, nos quoque concedimus; Quis autem de ipso sapiente aliter existimat, quin, etiam cum decreverit esse moriendum, tamen discessu a suis atque ipsa relinquenda luce moveatur? Duo Reges: constructio interrete. Quem enim ardorem studii censetis fuisse in Archimede, qui dum in pulvere quaedam describit attentius, ne patriam quidem captam esse senserit? Id quaeris, inquam, in quo, utrum respondero, verses te huc atque illuc necesse est.', 'Nec vero sum nescius esse utilitatem in historia, non modo voluptatem. Hanc in motu voluptatem -sic enim has suaves et quasi dulces voluptates appellat-interdum ita extenuat, ut M. Hunc ipsum Zenonis aiunt esse finem declarantem illud, quod a te dictum est, convenienter naturae vivere. Suo enim quisque studio maxime ducitur. Manebit ergo amicitia tam diu, quam diu sequetur utilitas, et, si utilitas amicitiam constituet, tollet eadem.', 'Partim cursu et peragratione laetantur, congregatione aliae coetum quodam modo civitatis imitantur; Hic nihil fuit, quod quaereremus. Stoici restant, ei quidem non unam aliquam aut alteram rem a nobis, sed totam ad se nostram philosophiam transtulerunt; Deinde disputat, quod cuiusque generis animantium statui deceat extremum. Tibi hoc incredibile, quod beatissimum. Sed haec ab Antiocho, familiari nostro, dicuntur multo melius et fortius, quam a Stasea dicebantur. Quid enim necesse est, tamquam meretricem in matronarum coetum, sic voluptatem in virtutum concilium adducere? Ne vitationem quidem doloris ipsam per se quisquam in rebus expetendis putavit, nisi etiam evitare posset.' ]; const container = document.getElementById('infoWindow'); const paragraphElements = paragraphs.map((paragraphText, index) => { const newParagraph = document.createElement('p'); newParagraph.innerHTML = paragraphText; newParagraph.style.animationDelay = `${.8 * index + 1}s`; return newParagraph; }); const demostrateScrolling = () => { const scroller = document.getElementById('scroller'); const scrollerOptions = { behavior: 'smooth', block: "start", inline: "nearest" }; scroller.addEventListener('click', () => { container.querySelector('p:last-child').scrollIntoView(scrollerOptions); }); paragraphElements.map(p => { container.appendChild(p); }); } document.addEventListener('DOMContentLoaded', demostrateScrolling); 
 body { font-family: 'Tahoma'; } #infoWindow { height: 200px; overflow-y: auto; margin: 10px; } #infoWindow p { padding: 10px; margin: 10px; background-color: navy; color: white; border-radius: 5px; animation-name: FadeIn; animation-duration: .4s; animation-fill-mode: backwards; } @keyframes FadeIn { from { opacity: 0; } to { opacity: 1; } } #scroller { width: auto; background-color: lightblue; border-radius: 24px; padding: 5px; margin: 5px; font-size: 10px; cursor: pointer; } 
 <h2>Scroll To Bottom</h2> <div id="infoWindow"></div> <span id="scroller">Scroll to bottom</span> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM