从锚链接到达后切换div

时间:2015-08-12 12:53:35

标签: javascript jquery toggle anchor-scroll

我的目标是创建一个平滑滚动到目的地的锚链接,然后到达它之后,切换类以打开手风琴。

我很难实现工作效果。滚动代码在这里:

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

我的网址中没有哈希。

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

谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用jQuery promisealways等待动画完成。这比动画回调更好(如果你已经在最终位置,则不会触发)

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

e.g。

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 切换元素:

e.g。

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;
});

答案 1 :(得分: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;
});