2015-09-30 94 views
2

當你登陸一個頁面時,我想讓背景圖像聚焦在圖像的底部,然後平移到圖像的頂部,然後返回下來並不斷重複。我有以下代碼:從下到上動畫背景圖像,連續重複jQuery

<body> 
    <div id="container"></div> 
</body> 

body { 
    height: 100%; 
    background-image: url(http://smmcnyc.com/work/apf/wp2/wp-content/uploads/2015/09/front-img2.jpg); 
    background-repeat: no-repeat; 
    background-position: 50% 100%; 
    background-attachment: fixed; 
} 
#container { 
    height: 100vh; 
} 

$(document).ready(function() { 
    $('body').animate({ 
     'background-position-x': '50%', 
     'background-position-y': '0' 
    }, { 
     duration: 500, 
    }); 
});  

爲什麼不能正常工作?我如何讓這個過程連續循環下去?我可以使用這段代碼,因爲Firefox不支持「background-position-x」,但jQuery不支持.animate()的「background-position」?

的jsfiddle是在這裏:https://jsfiddle.net/bqc8o2hn/2/

+0

我想你可以用CSS3動畫來做同樣的事情。 –

+0

與** [TweenMax](http://greensock.com/gsap)**,它只是一行代碼:https://jsfiddle.net/tahirahmed/bqc8o2hn/7/ –

回答

1

請檢查更新fiddle

body { 
    height: 100%; 
    background-image: url(http://smmcnyc.com/work/apf/wp2/wp-content/uploads/2015/09/front-img2.jpg); 
    background-repeat: no-repeat; 
    background-position: 50% 100%; 
    background-attachment: fixed; 
} 
body.loaded { 
    animation: bouncebg 5s ease; 
} 
@keyframes bouncebg { 
    0%, 100% { 
     background-position: 50% 100%; 
    } 
    50% { 
     background-position: 50% 0; 
    } 
} 
@-webkit-keyframes bouncebg { 
    0%, 100% { 
     background-position: 50% 100%; 
    } 
    50% { 
     background-position: 50% 0; 
    } 
} 
@-moz-keyframes bouncebg { 
    0%, 100% { 
     background-position: 50% 100%; 
    } 
    50% { 
     background-position: 50% 0; 
    } 
} 
#container { 
    height: 100vh; 
} 

更新JS代碼

$(document).ready(function() { 
    setTimeout(function(){ 
     $('body').addClass('loaded'); 
    }, 1000); 
});  

希望,這將有助於!

+0

這很好,直到我檢查它在IE11中!任何想法爲什麼這不起作用?提前致謝! – njpatten

+0

你可以嘗試使用'body.loaded {動畫:bouncebg 5s linear; }'。請提供您在IE11中看到的確切結果。更新小提琴:[鏈接](https://jsfiddle.net/bqc8o2hn/10/) –

2

這是你想要的嗎?我做了使用CSS轉換。

<body> 
    <div id="container"></div> 
</body> 


$(document).ready(function() { 
    $("body").toggleClass("to_top"); 
    window.setInterval(function(){ 
    $("body").toggleClass("to_top"); 
    },4000); 
});  

body { 
    height: 100%; 
    background-image: url(http://smmcnyc.com/work/apf/wp2/wp-content/uploads/2015/09/front-img2.jpg); 
    background-repeat: no-repeat; 
    background-position: 50% 100%; 
    background-attachment: fixed; 
    transition:all 2s; 
} 
#container { 
    height: 100vh; 
} 
.to_top{ 
    background-position: 50% 0%; 
} 
+0

這裏是jsfiddle:https://jsfiddle.net/bqc8o2hn/5/ –