我有一个问题清单。当我点击第一个问题时,它应该会自动将我带到页面底部的特定元素。
我怎么能用 jQuery 做到这一点?
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/
要将整个页面滚动到底部:
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
参考:scrollTop、scrollHeight、clientHeight
更新: 最新版本的 Chrome (61+) 和 Firefox 不支持滚动正文,请参阅:https://dev.opera.com/articles/fixing-the-scrolltop-bug/
香草 JS 实现:
element.scrollIntoView(false);
https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView
element.scrollIntoView({behavior: "smooth"});
您可以使用它以动画格式向下浏览页面。
$('html,body').animate({scrollTop: document.body.scrollHeight},"fast");
下面应该是跨浏览器解决方案。它已经在 Chrome、Firefox、Safari 和 IE11 上进行了测试
window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);
window.scrollTo(0,document.body.scrollHeight);不适用于 Firefox,至少对于 Firefox 37.0.2
一个衬垫平滑滚动到底部
window.scrollTo({ left: 0, top: document.body.scrollHeight, behavior: "smooth" });
要向上滚动,只需将 top
设置为 0
有时页面滚动到按钮(例如在社交网络中),向下滚动到最后(页面的最终按钮)我使用这个脚本:
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);
您可以在需要调用它的任何地方使用此函数:
function scroll_to(div){
if (div.scrollTop < div.scrollHeight - div.clientHeight)
div.scrollTop += 10; // move down
}
document.getElementById('copyright').scrollTop += 10
不起作用(在最新的 Chrome 中)......仍然为零......
仅 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,但我发现它在多种情况下很有帮助。
文档:flex
、flex-direction
、overflow-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; } 自动滚动演示:🐾
你也可以用动画来做到这一点,它非常简单
$('html, body').animate({
scrollTop: $('footer').offset().top
//scrollTop: $('#your-id').offset().top
//scrollTop: $('.your-class').offset().top
}, 'slow');
希望有帮助,谢谢
试图计算文档高度的答案太多了。但这对我来说计算不正确。但是,这两种方法都有效:
jQuery
$('html,body').animate({scrollTop: 9999});
或者只是 js
window.scrollTo(0,9999);
9999
长怎么办?
如果您想向下滚动到特定元素,这是一种简单的方法。
每当您想向下滚动时调用此函数。
函数 scrollDown() { document.getElementById('scroll').scrollTop = document.getElementById('scroll').scrollHeight } ul{ height: 100px;宽度:200px;溢出-y:滚动;边框:1px 实心#000; }
scroll
元素。
这是一种对我有用的方法:
预期结果:
没有滚动动画
首次加载时在页面底部加载
在页面底部加载所有刷新
代码:
<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
您可以将任何 id
附加到链接元素的引用属性 href
:
<a href="#myLink" id="myLink">
Click me
</a>
在上面的示例中,当用户点击页面底部的 Click me
时,导航会导航到 Click me
本身。
您可以尝试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 上应该没问题
派对迟到了,但这里有一些简单的纯 JavaScript 代码可以将任何元素滚动到底部:
function scrollToBottom(e) {
e.scrollTop = e.scrollHeight - e.getBoundingClientRect().height;
}
对于在 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)", "");
这是我的解决方案:
//**** 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)
我有一个包含动态内容的 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/
我找到了一个技巧来实现它。
将输入类型文本放在页面底部,并在需要进入底部时调用 jquery 焦点。
将其设为只读且漂亮的 css 以清除边框和背景。
如果有人在搜索 Angular
你只需要向下滚动添加到你的 div
#scrollMe [scrollTop]="scrollMe.scrollHeight"
<div class="my-list" #scrollMe [scrollTop]="scrollMe.scrollHeight">
</div>
这将保证滚动到底部
头部代码
<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">▼ Bottom ▼</a>
我有同样的问题。对我来说,在某个时间点,div 的元素没有完全加载,并且使用 scrollHeight 的当前值初始化了 scrollTop 属性,这不是 scrollHeight 的正确结束值。
我的项目在 Angular 8 中,我所做的是:
我使用 viewchild 来获取 .ts 文件中的元素。我继承了 AfterViewChecked 事件并在其中放置了一行代码,其中指出 viewchild 元素必须将 scrollHeight 的值纳入 scrollTop 值(this.viewChildElement.nativeElement.scrollTop = this.viewChildElement.nativeElement.scrollHeight;)
AfterViewChecked 事件触发了几次,它最终从 scrollHeight 中获得了正确的值。
我们可以使用 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"
>
会起作用的
一个简单的例子
$('html, body').animate({
scrollTop: $(this).height(),
});
:/ 它只是向下滚动到的开头
window.scrollTo(0,1e10);
总是有效。
1e10 是一个很大的数字。所以它总是页面的结尾。
一张图片胜过千言万语:
关键是:
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; }
不定期副业成功案例分享
element.scrollTop = element.scrollHeight
。objectSelector.scrollTo({ top: objectSelector.scrollHeight })
。了解objectSelector
是document.getElementById
返回的元素。 PD:在scrollTo
方法选项中添加behavior: 'smooth'
设置预定义的滚动动画。