当链接已经具有要滚动的锚点时,滚动到另一页面上的位置

时间:2015-06-04 11:40:46

标签: javascript jquery html

我在home page上有一个滚动到id位置的菜单:

<li><a href="#event-section">El evento</a></li>
<li><a href="#asistentes-section">Asistentes</a></li>
<li><a href="#contact-section">Contacto & Inscripciones</a></li>

我正在使用此脚本进行平滑滚动:

var $root = $('html, body');
$('a').click(function() {
    $root.animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);
    return false;
});

这很有效。

问题是我在网站上有另一个页面。当用户输入并点击菜单的任何链接时,由于divs仅存在于home page,因此无效。我希望如果用户在此其他页面中并单击菜单的链接,则home page将打开该部分。

任何想法如何修复此菜单才能做到这两件事?

4 个答案:

答案 0 :(得分:1)

尝试在除主页之外的所有其他页面中添加index.html然后哈希。这应该有用。

<li><a href="index.html#event-section">El evento</a></li>

答案 1 :(得分:1)

你可以使用这个脚本,需要动态意味着将哈希url滚动到那里。 例如:

<script>
if (window.location.href.trim().toLowerCase().indexOf('#event-section') > -1) {
    $('html, body').stop().animate({
        'scrollTop': $("a[href='#event-section']").offset().top
    }, 800, 'swing', function () {
    });
}
</script>

这是第一个链接页面为index.html#event-section。

答案 2 :(得分:1)

最简单的方法是为您要重定向最终用户的其他页面创建另一个导航栏

<li><a href="/index.php?id=event-section">El evento</a></li>
<li><a href="/index.php?id=asistentes-section">Asistentes</a></li>
<li><a href="/index.php?id=contact-section">Contacto & Inscripciones</a></li>

并在home page运行此script

<script>

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}


$(document).ready(function(){   
    var param_scroll = getParameterByName('id');
    if(param_scroll){
        $('html, body').animate({
            scrollTop: $("#"+param_scroll).offset().top
        }, 3000);   
    }
});


</script>

答案 3 :(得分:0)

如果你实现了这个功能,则不需要jQuery:

function scrollTo(anchorName) {
    location.hash = "#" + anchorName;
    return false;
}

在这种情况下,你链接应该是:

<a href="#anchorName">my_link</a>
相关问题