Javascript 滚动到第页的某个div
我试图在Javascript 滚动到第页的某个div,javascript,jquery,Javascript,Jquery,我试图在事件上滚动页面。单击事件。以下是我到目前为止的情况: jQuery: function scrollToStart() { $("#scrollToStart").click(function() { $("#startHere").animate({ scrollTop: 0 }, "slow"); return false; }); } HTML: 当我点击时,它什么也不做。我做错了什么?这应该行得通 $( document ).read
事件上滚动页面。单击事件。以下是我到目前为止的情况:
jQuery:
function scrollToStart() {
$("#scrollToStart").click(function() {
$("#startHere").animate({ scrollTop: 0 }, "slow");
return false;
});
}
HTML:
当我点击时,它什么也不做。我做错了什么?这应该行得通
$( document ).ready(function(){
$("#scrollToStart").click(function() {
$("#startHere").animate({ scrollTop: 0 }, "slow");
return false;
});});
$("#scrollToStart").click(function (){
$('html, body').animate({
crollTop: $("#startHere").offset().top
}, 2000);
});
小提琴
使用
$('html,body').animate({
scrollTop: $("#divToBeScrolledTo").offset().top;
});
使用scrollTop:0
时,您总是滚动到页面顶部
您可以在此处找到更多信息(通过实时演示):
我为我工作。如果我正确理解了问题,您需要在单击事件中将页面滚动到顶部位置,并具有动画效果。不久前我做了类似的事情,下面是JavaScript代码
innerAnimationStep = 25;
innerScrollStep = 1;
function scrollTopAnimated(scrollStep, animationStep)
{
try
{
innerScrollStep = scrollStep;
innerAnimationStep = animationStep;
scrollTopAnimationStep();
}
catch(e)
{
console.log(e.message);
}
}
function scrollTopAnimationStep()
{
try
{
var jDocument = $(document);
if(jDocument.scrollTop() > 0)
{
jDocument.scrollTop( jDocument.scrollTop() - innerScrollStep );
setTimeout(scrollTopAnimationStep, innerAnimationStep);
}
}
catch(e)
{
console.log(e.message);
}
}
只需调用scrollTopAnimated
即可获得具有动画效果的页面滚动。我希望这能有所帮助
$("#scrollToStart").bind('click',function() {
$('body , html').animate(
{
scrollTop : $("#startHere").offset().top
} , 2000 ) ;
});
你有JSFIDLE吗?因为你的滚动总是在页面的顶部。尝试将scrollTop:0
更改为scrollTop:500
何时调用scrollToStart()。您仅绑定到。调用该处理程序后,单击处理程序。您应该将其移动到一个准备好文档的handler为什么不使用锚?=>@RGraham-在脚本的不同部分调用它。这只是它的一部分。好吧,它确实有效:)我已经为此创建了一个js提琴,也许你正在使用一个普通的锚href=“#startHere”
?!!在这种情况下,您必须返回false代码>点击。防止默认设置和事件冒泡输入my friend;)刚刚看到它crollTop
。我在代码中修复了它,效果很好。谢谢
innerAnimationStep = 25;
innerScrollStep = 1;
function scrollTopAnimated(scrollStep, animationStep)
{
try
{
innerScrollStep = scrollStep;
innerAnimationStep = animationStep;
scrollTopAnimationStep();
}
catch(e)
{
console.log(e.message);
}
}
function scrollTopAnimationStep()
{
try
{
var jDocument = $(document);
if(jDocument.scrollTop() > 0)
{
jDocument.scrollTop( jDocument.scrollTop() - innerScrollStep );
setTimeout(scrollTopAnimationStep, innerAnimationStep);
}
}
catch(e)
{
console.log(e.message);
}
}
$("#scrollToStart").bind('click',function() {
$('body , html').animate(
{
scrollTop : $("#startHere").offset().top
} , 2000 ) ;
});