javascript 如何使用jquery滚动到模态中的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16072895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to scroll to an element within a modal using jquery?
提问by fat fantasma
I have an opened modal that I insert elements into line by line. Each line has it's own ID tag. Currently as the the list grows bigger than the modal window the text just gets hidden at the bottom of the modal window. You can manually use the scroll bar but I would like the text to scroll up in the modal window as they printed.
我有一个打开的模式,我将元素逐行插入。每行都有自己的 ID 标签。目前,当列表变得比模态窗口大时,文本只是隐藏在模态窗口的底部。您可以手动使用滚动条,但我希望文本在打印时在模式窗口中向上滚动。
I have played around with the following code but that just scrolls the webpage behind the modal. I have also tried replacing 'html, body' with modal elements to no avail.
我玩过以下代码,但这只是在模态后面滚动网页。我也试过用模态元素替换 'html, body' 无济于事。
$('html, body').animate({ scrollTop: $('#Element').offset().top }, 500);
I'm sure I close. Any suggestions?
我确定我关门了。有什么建议?
thanks
谢谢
采纳答案by Chris Traveis
It looks like you are calling the animate method on html and body.
看起来您是在 html 和 body 上调用 animate 方法。
$('html, body').animate(...);
If you want to scroll the modals window you have to call the animate method on that element instead.
如果要滚动模态窗口,则必须在该元素上调用 animate 方法。
$('#modal').animate(...);
Where #modal
is the element containing the elements you've created.
#modal
包含您创建的元素的元素在哪里。
edit:
编辑:
I see that you tried to call animate on the modal. Hereis a fiddle that scrolls elements in a modal when you click the button.
我看到你试图在模态上调用 animate 。 这是一个小提琴,当您单击按钮时,它会在模式中滚动元素。
also in the code you have a closing bracket after #Element
which is causing the script to error: ...scrollTop: $('#Element'])...
同样在代码中,您有一个右括号,之后#Element
会导致脚本出错:...scrollTop: $('#Element'])...
回答by Robert Bolton
If you want to see the contents that are getting hidden you can add a CSS style to the DIV to handle the overflow. This will automatically create a vertical scroll bar for you once the content exceeds the view area of DIV.
如果您想查看被隐藏的内容,您可以向 DIV 添加 CSS 样式以处理溢出。一旦内容超出 DIV 的视图区域,这将自动为您创建一个垂直滚动条。
$("#someDivID").css("overflow","auto");
All of the properties can be referenced at the URL below.
所有属性都可以在下面的 URL 中引用。
http://www.w3schools.com/cssref/pr_pos_overflow.asp
http://www.w3schools.com/cssref/pr_pos_overflow.asp
Hope that helps!
希望有帮助!