我正在寻找一种方法,当你在页面上或下点击一个指向本地锚的链接时,加入一个幻灯片效果.

我想要一些你有这样一个链接的东西:

<a href="#nameofdivetc">link text, img etc.</a>

可能添加了一个类,这样您就知道希望此链接成为滑动链接:

<a href="#nameofdivetc" class="sliding-link">link text, img etc.</a>

然后,如果单击此链接,页面会向上或向下滑动到所需的位置(可以是div、heading、页面顶部等).


这就是我之前所说的:

    $(document).ready(function(){
    $(".scroll").click(function(event){
        //prevent the default action for the click event
        event.preventDefault();

        //get the full url - like mysitecom/index.htm#home
        var full_url = this.href;

        //split the url by # and get the anchor target name - home in mysitecom/index.htm#home
        var parts = full_url.split("#");
        var trgt = parts[1];

        //get the top offset of the target anchor
        var target_offset = $("#"+trgt).offset();
        var target_top = target_offset.top;

        //goto that anchor by setting the body scroll top to anchor top
        $('html, body').animate({scrollTop:target_top}, 1500, 'easeInSine');
    });
});

推荐答案

描述

您可以使用jQuery.offset()jQuery.animate()来完成此操作.

看看jsFiddle Demonstration.

样本

function scrollToAnchor(aid){
    var aTag = $("a[name='"+ aid +"']");
    $('html,body').animate({scrollTop: aTag.offset().top},'slow');
}

scrollToAnchor('id3');

更多信息

Jquery相关问答推荐

将搜索面板和服务器端与POST AJAX请求一起使用时出现DataTables错误

如何在 jquery 中切换 attr()

如何在 jquery 中包含 !important

如何在 jquery 中从这个日期减go 一周?

jQuery中的正则表达式字段验证

如何判断是否有任何 JavaScript 事件侦听器/处理程序附加到元素/文档?

在不刷新页面的情况下更新网站的 CSS

禁用表单提交上的提交按钮

根据弹出框相对于窗口边缘的 X 位置更改 Bootstrap 弹出框的位置?

$(document).on('click', '#id', function() {}) 与 $('#id').on('click', function(){})

未捕获的 TypeError:data.push 不是函数

将打开/关闭图标添加到 Twitter Bootstrap 可折叠项(手风琴)

好处和.在本地托管 jQuery 的trap

如何签入用户已在 Google recaptcha 中选中复选框的 js?

Javascript 将 Markdown/Textile 转换为 HTML(理想情况下,返回 Markdown/Textile)

如何使用 jQuery 在悬停时显示工具提示消息?

延迟jquery悬停事件?

带有回调ajax json的jQuery自动完成

HTMLCollection、NodeLists 和对象数组之间的区别

JavaScript 在 DOM 中移动元素