结合jquery动画

时间:2014-11-26 08:52:13

标签: javascript jquery

我通过搜索查看了大部分内容。

第一个动画显示屏幕外的对象。

第二个动画使用url.com/#bottom

滚动到对象
$( "#contactbtn" ).click(function() {
    $( "#contactform" ).show( "fast", function() {
     // Animation complete.
    });
});



$('a[href^="#"]').on('click', function(event) {
    var target = $(this.href);
    if( target.length ) {
        event.preventDefault();
        $('html, body').animate({
            scrollTop: target.offset().top
        }, 1000);
    }
 });

每个动画都可以独立运作,但是当它们合并时,它们会立即发生并导致冲突 没有流体过渡到元素。想知道合并的方式,也许是通过延迟或排队。

2 个答案:

答案 0 :(得分:0)

你可以做这样的事情

var onClickFun = function() {
    $('a[href^="#"]').on('click', animateFun());
}

function animateFun()(event) {
var target = $(this.href);
if( target.length ) {
    event.preventDefault();
    $('html, body').animate({
        scrollTop: target.offset().top
    }, 1000);
}

$( "#contactbtn" ).click(function() {
$( "#contactform" ).show( "fast", onClickFun());

});

仅在第一个动画完成后调用第二个动画,并根据您的要求给出时滞。

答案 1 :(得分:0)

您是如此亲密-实际上,您的评论// Animation complete正是下一个动画的去向!

许多jQuery动画,包括show()animate(),都接受回调函数作为其最后一个参数。这样,仅在动画完成后,您才可以执行某些操作。对于您的示例,如果要显示联系表单,然后添加锚标签的侦听器:

$( "#contactbtn" ).click(function() {
    $( "#contactform" ).show( "fast", function() {
        //* Right here we are in the callback to the .show() method. 
        //* This code below is only run once the element has been shown.
        $('a[href^="#"]').on('click', function(event) {
            event.preventDefault();
            var target = $(this.href);
            if ( target.length ) {
                $('html, body').animate({
                    scrollTop: target.offset().top
                }, 1000);
            }
       });
    });
});

或者,您可以使scrollToAnchor拥有自己的功能。这样,您就可以保持代码整洁,并将其作为回调传递。回调函数按传递顺序接收参数。在这种情况下,事件对象将传递给scrollToAnchor。

您将看到此代码如何更具可读性和更易于维护。

function scrollToAnchor(e) {
    e.preventDefault();
    var target = $(this.href);
    if ( target.length ) {
        $('html, body').animate({
            scrollTop: target.offset().top
        }, 1000);
    }
}

$( "#contactbtn" ).click(function() {
    $( "#contactform" ).show( "fast", function() {
        //* Right here we are in the callback to the .show() method. 
        //* This code below is only run once the element has been shown.
        $('a[href^="#"]').on('click', scrollToAnchor);
    });
});
相关问题