【问题标题】:How to prevent angular behavior on anchor element?如何防止锚元素的角度行为?
【发布时间】:2015-03-23 09:07:38
【问题描述】:

我有一个带有以下锚线的 html 页面:

<a href="#help" class="button scrolly">

在同一页面中 - 当我单击此锚点时,我的页面会滚动到以下部分:

<section id="signup">

scrolly 类是一个 jquery 插件,用于使页面滚动到该部分。现在,角度改变锚点的行为,当我点击链接时 - 它会搜索一条名为“帮助”的路线。我如何防止这种行为并使锚只使用它的常规 HTML 行为?

我尝试将 href 从 #help 更改为 ##help - 但它使页面跳转并且没有实现滚动类脚本。

我尝试使用以下代码通过指令覆盖锚点并使用常规 jquery 滚动(忽略滚动类):

app.directive('a', function () {
    return {
        restrict: 'E',
        link: function (scope, elem, attrs) {
            if (attrs.href === '#help') {
                elem.on('click', function (e) {
                    var target = $(this.href);
                    if (target.length) {
                        event.preventDefault();
                        $('html, body').animate({
                            scrollTop: target.offset().top
                        }, 1000);
                    }
                });
            }
        }
    };
});

但它不起作用。

知道如何解决这个问题吗?

【问题讨论】:

  • 替换:var target = $(this.href);var target = $(this);

标签: javascript jquery html angularjs anchor


【解决方案1】:

我找到了答案 - 我的指令有一个错误 - 应该是:

app.directive('a', function () {
    return {
        restrict: 'E',
        link: function (scope, elem, attrs) {
            if (attrs.href === '#help') {
                elem.on('click', function (e) {
                    var target = $(attrs.href);
                    if (target.length) {
                        event.preventDefault();
                        $('html, body').animate({
                            scrollTop: target.offset().top
                        }, 1000);
                    }
                });
            }
        }
    };
});

我使用 attr.href 作为 jQuery DOM 元素名称。

无论如何 - 如果有另一个更简单的答案,我会链接知道它。

谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-22
    • 2022-08-08
    • 2011-11-10
    • 1970-01-01
    • 2023-03-06
    • 2020-10-06
    • 2013-05-13
    • 2016-08-18
    相关资源
    最近更新 更多