2013-11-09 25 views
6

滚动到特定的div我想使用jQuery如何使用jQuery或JavaScript

我写的代码一样滚动到特定的div:

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

但它没有移动到div位置。我怎样才能做到这一点jQuery的或JavaScript

回答

20

试试这个

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

.scrollTop()

8

尝试

.scrollTop()

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


scrollIntoView()

$('#dynamictabstrp')[0].scrollIntoView(true); 

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

下面是代码: -

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

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

Tr的这个简单的脚本。使用您特定的div ID或Class更改#targetDiv

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

的源代码,并现场演示可以从这里找到 - Smooth scroll to div using jQuery

0

你可以设置偏移按规定

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