ChatGPT解决这个技术问题 Extra ChatGPT

自动滚动到页面底部

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

我怎么能用 jQuery 做到这一点?


6
6 revs, 5 users 71%

jQuery 不是必需的。我从谷歌搜索中获得的大多数顶级结果都给了我这个答案:

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

如果您有嵌套元素,则文档可能不会滚动。在这种情况下,您需要定位滚动的元素并使用它的滚动高度。

window.scrollTo(0, document.querySelector(".scrollingContainer").scrollHeight);

您可以将其与问题的 onclick 事件(即 <div onclick="ScrollToBottom()" ...)联系起来。

您可以查看一些其他来源:

http://www.sourcetricks.com/2010/07/javascript-scroll-to-bottom-of-page.html

http://www.alecjacobson.com/weblog/?p=753

http://www.mediacollege.com/internet/javascript/page/scroll.html

http://www.electrictoolbox.com/jquery-scroll-bottom/


没有为我工作。我这样做了:element.scrollTop = element.scrollHeight
2016 年 5 月 4 日:请注意,“scrollTo”功能是实验性的,并不适用于所有浏览器。
scrollto 在我的浏览器上不起作用,我在 stackoverflow.com/questions/8917921/… 下方看到了这个链接,该链接非常有用,因为这些解决方案适用于我尝试过的浏览器。
对于单独的元素,这是有效的解决方案: document.querySelector(".scrollingContainer").scrollTo(0,document.querySelector(".scrollingContainer").scrollHeight);
这也应该有效:objectSelector.scrollTo({ top: objectSelector.scrollHeight })。了解 objectSelectordocument.getElementById 返回的元素。 PD:在 scrollTo 方法选项中添加 behavior: 'smooth' 设置预定义的滚动动画。
T
Tho

要将整个页面滚动到底部:

const scrollingElement = (document.scrollingElement || document.body);
scrollingElement.scrollTop = scrollingElement.scrollHeight;

您可以查看演示here

要将特定元素滚动到底部:

const scrollToBottom = (id) => {
    const element = document.getElementById(id);
    element.scrollTop = element.scrollHeight;
}

这是demo

它是这样工作的:

https://i.stack.imgur.com/iVYvW.png

参考:scrollTopscrollHeightclientHeight

更新: 最新版本的 Chrome (61+) 和 Firefox 不支持滚动正文,请参阅:https://dev.opera.com/articles/fixing-the-scrolltop-bug/


该解决方案适用于 Chrome、Firefox、Safari 和 IE8+。查看此链接了解更多详情quirksmode.org/dom/w3c_cssom.html
@luochenhuan,我刚刚使用“document.scrollingElement”而不是“document.body”修复了示例代码,见上文
s
shmuli

香草 JS 实现:

element.scrollIntoView(false);

https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView


使用 jQuery $('#id')[0].scrollIntoView(false);
目前它只是Firefox
现在可以在较新版本的 Chrome 中使用,但一些额外的选项(如平滑滚动)似乎还没有实现。
我在页面末尾添加了一个空 div 并使用了该 div 的 id。工作完美。
更好:element.scrollIntoView({behavior: "smooth"});
u
user5978325

您可以使用它以动画格式向下浏览页面。

$('html,body').animate({scrollTop: document.body.scrollHeight},"fast");

P
PixelsTech

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

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

window.scrollTo(0,document.body.scrollHeight);不适用于 Firefox,至少对于 Firefox 37.0.2


它在 Firefox 62.0.3 中确实有效,但我不知道他们什么时候修复了这个问题。
window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight); - 滚动不流畅。如何使滚动流畅@PixelsTech
您可以为滚动添加选项
T
TLJ

一个衬垫平滑滚动到底部

window.scrollTo({ left: 0, top: document.body.scrollHeight, behavior: "smooth" });

要向上滚动,只需将 top 设置为 0


此解决方案在 IE 中不起作用。我们是否可以添加任何锻炼以使其在 IE 中也能正常工作。
K
Konard

有时页面滚动到按钮(例如在社交网络中),向下滚动到最后(页面的最终按钮)我使用这个脚本:

var scrollInterval = setInterval(function() { 
    document.documentElement.scrollTop = document.documentElement.scrollHeight;
}, 50);

如果您在浏览器的 javascript 控制台中,能够停止滚动可能会很有用,因此添加:

var stopScroll = function() { clearInterval(scrollInterval); };

然后使用 stopScroll();

如果您需要滚动到特定元素,请使用:

var element = document.querySelector(".element-selector");
element.scrollIntoView();

或用于自动滚动到特定元素的通用脚本(或停止页面滚动间隔):

var notChangedStepsCount = 0;
var scrollInterval = setInterval(function() {
    var element = document.querySelector(".element-selector");
    if (element) { 
        // element found
        clearInterval(scrollInterval);
        element.scrollIntoView();
    } else if((document.documentElement.scrollTop + window.innerHeight) != document.documentElement.scrollHeight) { 
        // no element -> scrolling
        notChangedStepsCount = 0;
        document.documentElement.scrollTop = document.documentElement.scrollHeight;
    } else if (notChangedStepsCount > 20) { 
        // no more space to scroll
        clearInterval(scrollInterval);
    } else {
        // waiting for possible extension (autoload) of the page
        notChangedStepsCount++;
    }
}, 50);

让 size = ($("div[class*='card-inserted']")).length; ($("div[class*='card-inserted']"))[size -1].scrollIntoView();
@nobjta_9x_tq 这仅在页面加载到最后时才有效。
E
Em Seven

您可以在需要调用它的任何地方使用此函数:

function scroll_to(div){
   if (div.scrollTop < div.scrollHeight - div.clientHeight)
        div.scrollTop += 10; // move down

}

jquery.com: ScrollTo


对我来说,document.getElementById('copyright').scrollTop += 10 不起作用(在最新的 Chrome 中)......仍然为零......
a
ashleedawg

仅 CSS?!

一个有趣的纯 CSS 替代方案:

display: flex; 
flex-direction: column-reverse;

  /* ...probably usually along with: */

overflow-y: scroll;  /* or hidden or auto */
height: 100px; /* or whatever */

它是 not bullet-proof,但我发现它在多种情况下很有帮助。

文档flexflex-directionoverflow-y

演示:

var i=0, foo='Lorem Ipsum & foo in bar 或 blah ! on and '.split(' '); setInterval(function(){demo.innerHTML+=foo[i++%foo.length]+' '},200) #demo{ display:flex;弹性方向:列反向;溢出-y:滚动;宽度:150px;高度:150px;边框:3px 纯黑色; } body{ 字体系列:arial,无衬线;字体大小:15px; } 自动滚动演示:🐾


请注意,当使用多个元素(如段落)来显示文本时,这将在视觉呈现和 DOM 顺序之间造成脱节,这将对使用屏幕阅读器的用户产生负面影响。这种类型的用户将无法访问正确的阅读顺序。
R
Ricardo Vieira

你也可以用动画来做到这一点,它非常简单

$('html, body').animate({
   scrollTop: $('footer').offset().top
   //scrollTop: $('#your-id').offset().top
   //scrollTop: $('.your-class').offset().top
}, 'slow');

希望有帮助,谢谢


A
Andrew

试图计算文档高度的答案太多了。但这对我来说计算不正确。但是,这两种方法都有效:

jQuery

    $('html,body').animate({scrollTop: 9999});

或者只是 js

    window.scrollTo(0,9999);

大声笑“工作”。如果 the document9999 长怎么办?
@DanDascalescu 99999
如果文档长度超过 99999 怎么办?!
@BrendonMuir如果文档长于99999,您可以在获取文档动态高度的答案中的javascript代码上方定义一个javascript变量,并使用该变量而不是硬编码的99999
对不起@nviens,我只是很傻,跟着 DanDascalescu :D
L
Liam

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

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

函数 scrollDown() { document.getElementById('scroll').scrollTop = document.getElementById('scroll').scrollHeight } ul{ height: 100px;宽度:200px;溢出-y:滚动;边框:1px 实心#000; }

  • Top Here
  • Something Here
  • Something Here
  • Something Here
  • Something Here
  • 这里有些东西
  • 这里有些东西
  • 这里有些东西
  • 这里有些东西
  • 这里有些东西
  • < li>这里的底部
  • 这里的底部


这不是 simple,需要创建一个 scroll 元素。
@DanDascalescu 你是对的!但我的代码有效我认为它不值得投票
“作品”是不够的。此页面上的所有解决方案都在某种程度上“有效”。而且有很多。读者应该如何决定?
O
ObjectJosh

这是一种对我有用的方法:

预期结果:

没有滚动动画

首次加载时在页面底部加载

在页面底部加载所有刷新

代码:

<script>
    function scrollToBottom() {
        window.scrollTo(0, document.body.scrollHeight);
    }
    history.scrollRestoration = "manual";
    window.onload = scrollToBottom;
</script>

为什么这可能对其他方法有效:

诸如 Chrome 之类的浏览器有一个内置预设,可以在刷新后记住您在页面上的位置。仅 window.onload 不起作用,因为您的浏览器会在您调用以下行之后自动将您滚动回刷新之前的位置:

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

这就是为什么我们需要添加:

history.scrollRestoration = "manual";

window.onload 之前先禁用该内置功能。

参考:

window.onload 的文档:https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload

window.scrollTo 的文档:https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo

history.scrollRestoration 的文档:https://developer.mozilla.org/en-US/docs/Web/API/History/scrollRestoration


谢谢-这是搜索了几天后对我有用的答案。
R
RegarBoy

您可以将任何 id 附加到链接元素的引用属性 href

<a href="#myLink" id="myLink">
    Click me
</a>

在上面的示例中,当用户点击页面底部的 Click me 时,导航会导航到 Click me 本身。


这不适合我,因为它会更改 url,然后我的 Angular 应用程序会重定向到其他东西!
A
Ahsan Khurshid

您可以尝试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 火狐、Safari、Opera

Windows 火狐、Opera、Safari、Internet Explorer 5.55+

Linux 未经测试,但至少在 Firefox 上应该没问题


S
ShortFuse

派对迟到了,但这里有一些简单的纯 JavaScript 代码可以将任何元素滚动到底部:

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

X
Xpleria

对于在 Selenium 中向下滚动,请使用以下代码:

直到底部下拉,滚动到页面的高度。使用以下在 JavaScript 和 React 中都可以正常工作的 JavaScript 代码。

JavascriptExecutor jse = (JavascriptExecutor) driver; // (driver is your browser webdriver object) 
jse.executeScript("window.scrollBy(0,document.body.scrollHeight || document.documentElement.scrollHeight)", "");

I
Iamma Iamma

这是我的解决方案:

 //**** scroll to bottom if at bottom

 function scrollbottom() {
    if (typeof(scr1)!='undefined') clearTimeout(scr1)   
    var scrollTop = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
    var scrollHeight = (document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight;
    if((scrollTop + window.innerHeight) >= scrollHeight-50) window.scrollTo(0,scrollHeight+50)
    scr1=setTimeout(function(){scrollbottom()},200) 
 }
 scr1=setTimeout(function(){scrollbottom()},200)

那里……到底发生了什么?关心你解释你的解决方案吗?不鼓励仅使用代码的答案。
C
Ciarán Bruen

我有一个包含动态内容的 Angular 应用程序,我尝试了上述几个答案,但没有取得多大成功。我改编了@Konard 的答案,并让它在我的场景中使用纯 JS:

HTML

<div id="app">
    <button onClick="scrollToBottom()">Scroll to Bottom</button>
    <div class="row">
        <div class="col-md-4">
            <br>
            <h4>Details for Customer 1</h4>
            <hr>
            <!-- sequence Id -->
            <div class="form-group">
                <input type="text" class="form-control" placeholder="ID">
            </div>
            <!-- name -->
            <div class="form-group">
                <input type="text" class="form-control" placeholder="Name">
            </div>
            <!-- description -->
            <div class="form-group">
                <textarea type="text" style="min-height: 100px" placeholder="Description" ></textarea>
            </div>
            <!-- address -->
            <div class="form-group">
                <input type="text" class="form-control" placeholder="Address">
            </div>
            <!-- postcode -->
            <div class="form-group">
                <input type="text" class="form-control" placeholder="Postcode">
            </div>
            <!-- Image -->
            <div class="form-group">
                <img style="width: 100%; height: 300px;">
                <div class="custom-file mt-3">
                    <label class="custom-file-label">{{'Choose file...'}}</label>
                </div>
            </div>
            <!-- Delete button -->
            <div class="form-group">
                <hr>
                <div class="row">
                    <div class="col">
                        <button class="btn btn-success btn-block" data-toggle="tooltip" data-placement="bottom" title="Click to save">Save</button>
                        <button class="btn btn-success btn-block" data-toggle="tooltip" data-placement="bottom" title="Click to update">Update</button>
                    </div>
                    <div class="col">
                        <button class="btn btn-danger btn-block" data-toggle="tooltip" data-placement="bottom" title="Click to remove">Remove</button>
                    </div>
                </div>
                <hr>
            </div>
        </div>
    </div>
</div>

CSS

body {
    background: #20262E;
    padding: 20px;
    font-family: Helvetica;
}

#app {
    background: #fff;
    border-radius: 4px;
    padding: 20px;
    transition: all 0.2s;
}

JS

function scrollToBottom() {
    scrollInterval;
    stopScroll;

    var scrollInterval = setInterval(function () {
        document.documentElement.scrollTop = document.documentElement.scrollHeight;
    }, 50);

    var stopScroll = setInterval(function () {
        clearInterval(scrollInterval);
    }, 100);
}

在最新的 Chrome、FF、Edge 和现有的 Android 浏览器上进行了测试。这是一个小提琴:

https://jsfiddle.net/cbruen1/18cta9gd/16/


J
Julien

我找到了一个技巧来实现它。

将输入类型文本放在页面底部,并在需要进入底部时调用 jquery 焦点。

将其设为只读且漂亮的 css 以清除边框和背景。


A
Akitha_MJ

如果有人在搜索 Angular

你只需要向下滚动添加到你的 div

 #scrollMe [scrollTop]="scrollMe.scrollHeight"

   <div class="my-list" #scrollMe [scrollTop]="scrollMe.scrollHeight">
   </div>

S
SeekLoad

这将保证滚动到底部

头部代码

<script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<script language="javascript" type="text/javascript">
function scrollToBottom() {
  $('#html, body').scrollTop($('#html, body')[0].scrollHeight);
}
</script>

正文代码

<a href="javascript:void(0);" onmouseover="scrollToBottom();" title="Scroll to Bottom">&#9660; Bottom &#9660;</a>

D
Dharman

我有同样的问题。对我来说,在某个时间点,div 的元素没有完全加载,并且使用 scrollHeight 的当前值初始化了 scrollTop 属性,这不是 scrollHeight 的正确结束值。

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

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

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


A
Arti

我们可以使用 ref 和 getElementById 来滚动特定的 modal 或 page 。

 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"
        >

会起作用的


J
Joukhar

一个简单的例子

$('html, body').animate({
    scrollTop:   $(this).height(),
  });

嗯,不适用于 Google Chrome 100 中的巨大
 :/ 它只是向下滚动到 
 的开头
                        				                   		
T
Timar Ivo Batis

window.scrollTo(0,1e10);

总是有效。

1e10 是一个很大的数字。所以它总是页面的结尾。


n
nonopolarity

一张图片胜过千言万语:

关键是:

document.documentElement.scrollTo({
  left: 0,
  top: document.documentElement.scrollHeight - document.documentElement.clientHeight,
  behavior: 'smooth'
});

它使用的是 document.documentElement,即 <html> 元素。就像使用 window,但我个人更喜欢这样做,因为如果它不是整个页面而是一个容器,它就像这样工作,除了你要更改 document.body 和 {1 } 到 document.querySelector("#container-id")

例子:

让 cLines = 0; let timerID = setInterval(function() { let elSomeContent = document.createElement("div"); if (++cLines > 33) { clearInterval(timerID); elSomeContent.innerText = "这就是所有人!"; } else { elSomeContent .innerText = new Date().toLocaleDateString("en", { dateStyle: "long", timeStyle: "medium" }); } document.body.appendChild(elSomeContent); document.documentElement.scrollTo({ left: 0,顶部:document.documentElement.scrollHeight - document.documentElement.clientHeight,行为:'smooth' }); }, 1000);正文 {字体:27px Arial,无衬线;背景:#ffc;颜色:#333; }

如果没有 scrollTo(),您可以比较差异:

让 cLines = 0; let timerID = setInterval(function() { let elSomeContent = document.createElement("div"); if (++cLines > 33) { clearInterval(timerID); elSomeContent.innerText = "这就是所有人!"; } else { elSomeContent .innerText = new Date().toLocaleDateString("en", { dateStyle: "long", timeStyle: "medium" }); } document.body.appendChild(elSomeContent); }, 1000);正文 {字体:27px Arial,无衬线;背景:#ffc;颜色:#333; }