![](/img/trans.png)
[英]Using JQuery or Javascript, how can I tie a click function to control the scroll of an element/div?
[英]How can I scroll to an element using jQuery?
我希望頁面滾動到頁面頂部的 div。 我有頁面其他部分的按鈕,但是當我滾動到底部並單擊按鈕時,這不起作用。 它不會轉到頁面頂部。
這是 CodePen: https ://codepen.io/Filizof/pen/xygWyp?editors=1010
$(document).ready(function() {
$("#btn1").click(function() {
$("body").scrollTo("#menudiv");
});
});
如果你想用“純 JavaScript”平滑地滾動到一個元素,你可以這樣做:
document.querySelector('#menudiv').scrollIntoView({
behavior: 'smooth'
});
更多信息在這里: Element.scrollIntoView()
注意:請參閱我可以使用... HTML5、CSS3 等支持表以獲取最新的瀏覽器支持...
如果您想使用 jQuery 平滑地滾動到某個元素,那么您可以執行以下操作:
$(document).ready(function() {
$(".btns").click(function() {
$("html").animate(
{
scrollTop: $("#menudiv").offset().top
},
800 //speed
);
});
});
示例: https ://jsbin.com/xaciloteqe/1/edit?html,js,output
這可能對研究此主題的人有所幫助:
JavaScript 有element.scrollIntoView()
函數。
就像是:
$("#menudiv")[0].scrollIntoView()
您可以使用簡單的 JS 來完成這項工作。 scrollIntoView() 滾動到可見區域。
像這樣的東西:
var elmnt = document.getElementById("content");
elmnt.scrollIntoView();
<script type="text/javascript" src="jquery-3.2.1.js">
用。。。來代替
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
我稍微更新了你的代碼,它應該是:
$(document).ready(function() {
$("#btn1").click(function()
{
var elmnt = document.getElementById("menudiv");
elmnt.scrollIntoView();
});
});
要滾動到 div/元素,它是 scrollIntoView HTML DOM 方法。 它不是一個 jQuery 函數。
這是代碼筆: JS Scroll to an Element
由於一些markdownify插件,我遇到了一個小問題,無論如何我必須搜索鏈接的目標,所以我使用了這個解決方法。 它實際上適用於各種元素選擇器,在我的情況下,我的鏈接是<a href="#target">some text</a>
而我的實際目標是<a href="target"></a>
特殊情況我可以給你這個解決方案:
var scrollAnchorSamePage = function() {
$('a[href^="#"]').click(function() {
event.preventDefault();
var id = $(this).attr("href");
// okay lets remove the hashtag in front:
var target = $('a[href^="' + id.substring(1, id.length) + '"]');
// and I need a little offset due to a fixed sticky header by 140
$('html, body').animate({ scrollTop: target.offset().top - (160) }, 1000);
});
}
scrollAnchorSamePage();
PS:我使用以下 jQuery 包導入,您可以在 DOM 中關閉</body>
html 標記之前添加它們。
<!-- Latest minified jQuery -->
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<!-- Latest compiled and minified bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
檢查此: https : //codepen.io/anon/pen/ePyzoj?editors=1010
$("#btn1").click(function() {
$([document.documentElement, document.body]).animate({
scrollTop: $("#menudiv").offset().top
}, 2000);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.