jQuery动画和窗口大小调整

时间:2013-06-07 18:43:02

标签: jquery animation resize window

我认为问这个的最好方法是只显示代码:

var counter = 1;
$('#animation').click(function () {
    if (!$('h2').is(':animated')) {
        if (counter == 5) {
            toTheRight = !toTheRight;
            counter = 0;
        }
        var movement = (.2 * $('h2').width()) + "px";
        if (toTheRight) {
            $('h2').animate({
                "font-size": "2.2em",
                "width": "50%",
                "left": "+=" + movement
            }, { queue: false, duration: 1000 });
        }
        else {
            $('h2').animate({
                "font-size": "2.2em",
                "width": "50%",
                "left": "-=" + movement
            }, { queue: false, duration: 1000 });
        }
        counter++;
    }
});

此功能非常适用于从开始到结束保持相同大小的窗口。我想知道是否有一种优雅的方式来处理窗口调整大小,而不仅仅是将元素的当前位置一直重新向左移动。

注意:如果处于全屏模式且元素一直向右,减少屏幕而不调整元素位置会导致元素滚动到屏幕右侧。

感谢您提供任何建议。

1 个答案:

答案 0 :(得分:0)

想出来,结束了重写一些事情

$('#animation').click(function () {
    if (!$('h2').is(':animated')) {
        var myColors = ["orange", "green", "cyan", "magenta", "red"];
        var myMessages = ["Of the people", "By the people", "For the people", "EAGLE!"];
        $('h2').css("background-color", myColors[counter % 5]);
        if (counter == 5) {
            toTheRight = !toTheRight;
            counter = 0;
            $('#mutate').each(function (index, element) {
                if (element.firstChild.data == myMessages[0]) {
                    element.firstChild.data = myMessages[1];
                }
                else if (element.firstChild.data == myMessages[1]) {
                    element.firstChild.data = myMessages[2];
                }
                else if (element.firstChild.data == myMessages[2]) {
                    element.firstChild.data = myMessages[3];
                }
                else {
                    element.firstChild.data = myMessages[0];
                }
            });
        }
        var movement = (.1 * $('#crazy').width()) + "px";
        if (toTheRight) {
            $('h2').animate({
                "font-size": "2.2em",
                "width": "50%",
                "left": "+=" + movement
            }, { queue: false, duration: 1000 });
        }
        else {
            $('h2').animate({
                "font-size": "2.2em",
                "width": "50%",
                "left": "-=" + movement
            }, { queue: false, duration: 1000 });
        }
        counter++;
    }
});


$(window).resize(function () {
    if (!$('h2').is(':animated')) {
        var tempCounter;
        if (toTheRight) {
            tempCounter = counter;
        }
        else {
            tempCounter = 5 - counter;
        }
        var positionPercent = tempCounter * .1;
        var leftPosition = positionPercent * ($('#crazy').width()) + "px"
        $('h2').css("left", leftPosition);

    }
});

当窗口从非常大到非常小时,只有轻微的瑕疵,效果相当好。