Redirect to a div on a different page with smooth

2019-02-08 03:26发布

Question Background:

I have a 2 page website. Both pages use the same masterlayout.cshtml page which features a Navbar. Within the Navbar is a number of links which scroll down to the relevant divs on page one based on their ID's.

The Issue:

When I access the second page I can no longer redirect to the specified divs from the Navbar links on the first page. This makes sense as the focus is no longer on the first page, but how do I get around this issue?

Code:

Here is the Navbar code with the div id's set, note the data-id attributes specifying which div to scroll to:

        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li><a href="#" class="scroll-link" data-id="Welcome">Welcome</a></li>
                <li><a href="#" class="scroll-link" data-id="features">Club</a></li>
                <li><a href="#" class="scroll-link" data-id="About">About Us</a></li>
                <li><a href="#" class="scroll-link" data-id="Location">Location</a></li>
                <li><a href='@Url.Action("FutureEvents", "Events", new { pageNo = 1 })'>Events</a></li>
            </ul>
        </div> 

Example of a div that is scrolled to:

        <div id="Welcome">
             //HTML
        </div>

The JQuery used to Scroll to the relevant div:

        function scrollToID(id, speed) {
          var offSet = 70;
          var obj = $(id).offset();
          var targetOffset = $(id).offset().top - offSet;
          $('html,body').animate({ scrollTop: targetOffset }, speed);
        }

If anyone can help with coming up with a viable solution to being able to call these id's from a different page that would be great.

8条回答
淡お忘
2楼-- · 2019-02-08 04:24

You can track hash of page url and scroll page to particular div

<a href="#Welcome" class="scroll-link">Welcome</a>
<a href="your_page_url#Welcome" class="other-page">Welcome</a> <!-- link to other page scroll div -->

Jquery

$(document).ready(function(){
    var speed = 1000;

    // check for hash and if div exist... scroll to div
    var hash = window.location.hash;
    if($(hash).length) scrollToID(hash, speed); 

    // scroll to div on nav click
    $('.scroll-link').click(function (e) {
        e.preventDefault();
        var id = $(this).attr('href');
        if($(id ).length) scrollToID(id, speed);
    });
})

function scrollToID(id, speed) {
    var offSet = 70;
    var obj = $(id).offset();
    var targetOffset = obj.top - offSet;
    $('html,body').animate({ scrollTop: targetOffset }, speed);
}
查看更多
Summer. ? 凉城
3楼-- · 2019-02-08 04:24

You can send the ID of the div, that you want to scroll to, to the second page through a URL query string and write a script (in page 2) to read the URL and scroll to the specified div. Piece of cake.

查看更多
登录 后发表回答