我有一份问题清单。当我点击第一个问题时,它会自动把我带到页面底部的特定元素。

我如何用jQuery做到这一点?


当前回答

我们可以使用ref和by getElementById滚动特定的模态或页面。

 const scrollToBottomModel = () => {
    const scrollingElement = document.getElementById("post-chat");
    scrollingElement.scrollTop = scrollingElement.scrollHeight;
  };

在模态体中,你可以调用上面的函数

 <Modal.Body
          className="show-grid"
          scrollable={true}
          style={{
            maxHeight: "calc(100vh - 210px)",
            overflowY: "auto",
            height: "590px",
          }}
          ref={input => scrollToBottomModel()}
          id="post-chat"
        >

会起作用

其他回答

如果您想向下滚动到特定元素,这是一种简单的方法。

当您想向下滚动时,请调用此函数。

function scrollDown() { document.getElementById('scroll').scrollTop = document.getElementById('scroll').scrollHeight } ul{ height: 100px; width: 200px; overflow-y: scroll; border: 1px solid #000; } <ul id='scroll'> <li>Top Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Bottom Here</li> <li style="color: red">Bottom Here</li> </ul> <br /> <button onclick='scrollDown()'>Scroll Down</button>

下面是跨浏览器的解决方案。它已经在Chrome、Firefox、Safari和IE11上进行了测试

window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);

window.scrollTo (0, document.body.scrollHeight);不能在Firefox上运行,至少不能在Firefox 37.0.2上运行

我也遇到过同样的问题。对于我来说,在一个时间点上,div的元素没有完全加载,scrollTop属性是用scrollHeight的当前值初始化的,这不是scrollHeight的正确结束值。

我的项目在Angular 8中,我所做的是:

我使用viewchild来获取.ts文件中的元素。 我已经继承了AfterViewChecked事件,并在那里放置了一行代码,其中声明viewchild元素必须将scrollTop值的值scrollHeight (this.viewChildElement.nativeElement。scrollTop = this.viewChildElement.nativeElement.scrollHeight;)

AfterViewChecked事件触发了几次,它最终从scrollHeight中获得了正确的值。

你可以试试Gentle Anchors,一个不错的javascript插件。

例子:

function SomeFunction() {
  // your code
  // Pass an id attribute to scroll to. The # is required
  Gentle_Anchors.Setup('#destination');
  // maybe some more code
}

兼容性测试对象:

Mac Firefox, Safari, Opera Windows Firefox, Opera, Safari, Internet Explorer 5.55+ Linux未经测试,但至少Firefox应该没问题

来晚了,但这里有一些简单的javascript代码,可以将任何元素滚动到底部:

function scrollToBottom(e) {
  e.scrollTop = e.scrollHeight - e.getBoundingClientRect().height;
}