简体   繁体   English

如何使用jquery或javascript滚动到特定的div

[英]How to scroll to the particular div using jquery or javascript

I want to scroll to the particular div using jquery 我想使用jquery滚动到特定的div

I have written the code like: 我写的代码如下:

 $("#button").on('click',function(){
     var p = $("#dynamictabstrp");
     var offset = p.offset();
     window.scrollBy(offset.left, offset.top);
 });

But it is not moving to the div position. 但它没有转向div的位置。 How can i do that in jquery or javascript 我怎么能在jquery或javascript中做到这一点

Try this 试试这个

$("#button").on('click',function() {
    $('html, body').animate({
        'scrollTop' : $("#dynamictabstrp").position().top
    });
});

.scrollTop() .scrollTop()

Try 尝试

.scrollTop() .scrollTop()

$(window).scrollTop($('#dynamictabstrp').offset().top);


or 要么

scrollIntoView() scrollIntoView()

document.getElementById('dynamictabstrp').scrollIntoView(true);

or 要么

 document.getElementById('dynamictabstrp').scrollIntoView(true); 

Here is the code :- 这是代码: -

$(document).ready(function (){
  $("#button").on('click',function(){                
         $('html, body').animate({
              scrollTop: $("#dynamictabstrp").offset().top
        }, 1000);               
    });
});

or 要么

$(document).ready(function (){
  $("#button").click(function(){                
         $('html, body').animate({
              scrollTop: $("#dynamictabstrp").offset().top
        }, 1000);               
    });
});

Try this simple script. 试试这个简单的脚本。 Change #targetDiv with your particular div ID or Class. 使用您的特定div ID或Class更改#targetDiv

$('html,body').animate({
    scrollTop: $('#targetDiv').offset().top
}, 1000);

The source code and live demo can be found from here - Smooth scroll to div using jQuery 源代码和现场演示可以在这里找到 - 使用jQuery平滑滚动到div

You can set offset as per requirement 您可以根据需要设置偏移量

jQuery(document).ready(function(){
function secOffset(){
                        jQuery('html, body').animate({
                        scrollTop: jQuery(window.location.hash).offset().top - 60
                }, 0);
        }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM