1

我的目标是创建锚链接,平滑滚动到其目的地,并在到达目的地后,切换类以打开手风琴。

我很难取得工作成果。滚动代码在这里:

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

我的网址中没有哈希。

如何在此滚动代码中包含切换?

谢谢!

4

2 回答 2

2

您可以使用 jQuerypromisealways. 这比动画回调更好(如果您已经在最终位置,则不会触发)

JSFiddle http://jsfiddle.net/fb6yuf9k/1/

例如

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

对于评论中提供的特定网站,您希望toggle-content 在目标元素下方切换元素

例如

var $root = $('html, body');
$('.calendar a').click(function () {
    var $target = $($.attr(this, 'href'));
    $root.animate({
        scrollTop: $target.offset().top
    }, 500).promise().always(function(){
        $target.find('.toggle-content').toggle(); // or toggleClass etc
    });
    return false;
});
于 2015-08-12T13:08:29.820 回答
2

有一个“完成”函数回调,您可以在动画结束时粘贴,如下所示:

var $root = $('html, body');
$('.calendar a').click(function() {
$root.animate({
    scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500, function() {
 //DO YOUR TOGGLE HERE
 $('#target').toggleClass('myClass')
});
return false;
});
于 2015-08-12T13:09:30.863 回答