如何从其他页面重定向后将页面滚动到元素?

时间:2013-05-26 07:05:21

标签: jquery redirect

<script>
    $(document).ready(function () {
        $("#button").click(function () {
            window.location.href = "page2.aspx"; 

            $('html, body').animate({ 
                scrollToElement ("#div").offset().top 
            }, 2000); 
        }); 
    });
</script>

这个想法是,你单击第1页上的按钮,然后你被重定向到page2,然后你使用jQuery滚动到一个特定的元素。

1 个答案:

答案 0 :(得分:12)

您始终可以为该元素设置锚点,如此

<a name="scroll"></a>
<h2>I wanna scroll here</h2>

并链接到它:http://mydomain.com/index.php#scroll

使用jQuery执行此任务的唯一好处是为滚动本身设置动画,在这种情况下,您可以执行以下操作:

<h2 id="scrollhere">I wanna scroll here</h2>

此处链接:http://mydomain.com/index.php#scrollhere

然后在重定向页面的jQuery中:

$(document).ready(function() {
    if (window.location.hash != null && window.location.hash != '') 
        $('body').animate({
            scrollTop: $(window.location.hash).offset().top
        }, 1500);
});