我有一份问题清单。当我点击第一个问题时,它会自动把我带到页面底部的特定元素。
我如何用jQuery做到这一点?
我有一份问题清单。当我点击第一个问题时,它会自动把我带到页面底部的特定元素。
我如何用jQuery做到这一点?
当前回答
香草JS实现:
element.scrollIntoView(false);
https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView
其他回答
CSS-Only ? !
一个有趣的css替代方案:
display: flex;
flex-direction: column-reverse;
/* ...probably usually along with: */
overflow-y: scroll; /* or hidden or auto */
height: 100px; /* or whatever */
它不是万无一失的,但我发现它在一些情况下很有帮助。
文档:flex, flex-direction, overflow-y
演示:
var i=0, foo='Lorem Ipsum & foo在酒吧或blah !和“。分割(' '); setInterval(函数(){demo.innerHTML + = foo [i + + % foo。长度)+ ' '},200) #{演示显示:flex; flex-direction: column-reverse; overflow-y:滚动; 宽度:150 px; 身高:150 px; 边框:3px纯黑色;} 身体{字体类型:arial,无衬线; 字体大小:15 px;} Autoscrolling演示:& # x1f43e; < div id =“演示”> < / div >
我们可以使用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"
>
会起作用
以下是我的解决方案:
//**** 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)
jQuery不是必需的。我从谷歌搜索中得到的大多数结果都是这样的答案:
window.scrollTo(0, document.body.scrollHeight);
在有嵌套元素的地方,文档可能无法滚动。在这种情况下,您需要以滚动的元素为目标,并使用其滚动高度。
nestedElement.scrollTo(0, nestedElement.scrollHeight);
你可以参考一些其他的来源:
http://www.alecjacobson.com/weblog/?p=753 http://www.mediacollege.com/internet/javascript/page/scroll.html http://www.electrictoolbox.com/jquery-scroll-bottom/
如果在您想要滚动到的位置或附近的任何类型的标记中有一个ID,那么只需使用scrollIntoView函数编写一行JavaScript即可。例如,假设您所讨论的元素是ID为“mydiv1”的DIV
<div id="mydiv1">[your contents]</div>
然后运行JavaScript命令
document.getElementById("mydiv1").scrollIntoView();
根本不需要JQuery。 希望这能有所帮助。