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

gab*_*apo 3 jquery redirect

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

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

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

cas*_*raf 12

您总是可以为该元素设置锚点,就像这样

<a name="scroll"></a>
<h2>I wanna scroll here</h2>
Run Code Online (Sandbox Code Playgroud)

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

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

<h2 id="scrollhere">I wanna scroll here</h2>
Run Code Online (Sandbox Code Playgroud)

链接在这里: 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);
});
Run Code Online (Sandbox Code Playgroud)