繁体   English   中英

单击锚标记时添加效果

[英]Adding effects when anchor tag is clicked

是否可以通过单击锚点将类添加到正在滚动到的任何div?

我目前有此代码,但只能将“ animated swing”类添加到#ecomm div中。

理想情况下,我单击的页面上的任何锚点不仅要向下滚动到该锚点,还要添加一个动画类。

到目前为止,我的代码:

<script>
$('a[href=#ecomm]').click(function(){
  $("#ecomm").addClass( "animated swing" );
    $('html, body').animate({
    scrollTop: $( $.attr(this, 'href') ).offset().top
     }, 500);
     return false;
  });
</script>

应与所有锚标签工作#的HREF。

<script>
    $('a[href^=#]').click(function () { // Use all anchor tags with an href that starts with #
        var href = $(this).attr('href'); // Get the href for the clicked anchor.
        $(href).addClass( "animated swing" ); // The href is the same as the id.
        $('html, body').animate({
            scrollTop: $(href).offset().top
        }, 500);
        return false;
    });
</script>

考虑到@ rorypicko的评论,可以增加一个数据属性,以确保只有#你需要使用这个功能的HREF:

<a href="#ecomm" data-scroll-link>Text</a>
<script>
    $('a[href^=#][data-scroll-link]').click(function () { // Use all anchor tags with an href that starts with # and the specified data attribute.
        var href = $(this).attr('href'); // Get the href for the clicked anchor.
        $(href).addClass( "animated swing" ); // The href is the same as the id.
        $('html, body').animate({
            scrollTop: $(href).offset().top
        }, 500);
        return false;
    });
</script>

像这样的东西:

<script>
    var href
    $('a').click(function(){
        href = this.attr('href');
        $('div').each(function(){
            var thisDiv = this
            if(this.attr('id') == href)
            {
                thisDiv.addClass( "animated swing" );
            }
            $('html, body').animate({
                scrollTop: thisDiv.offset().top
            }, 500);
        });
        return false;
     });
</script>


希望这行得通。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM