页面很简单,代码不多,只有两幅背景图,一个背景色,想做成视差滚动,但不知道哪里出了问题,特来请教:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>背景视差滚动</title> 5 <meta charset="utf-8" /> 6 </head> 7 <style type="text/css"> 8 body { 9 background-color: #252525; 10 background-image: url(img/parallax-back.png); 11 background-attachment: fixed !important; 12 background-clip: border-box; 13 background-origin: padding-box; 14 background-position: 0 0; 15 background-repeat: repeat; 16 background-size: auto auto; 17 height: 2000px; 18 } 19 20 #parallax-fore { 21 background-attachment: fixed; 22 background-image: url(img/parallax-fore.png); 23 height: 100vh; 24 left: 0; 25 pointer-events: none; 26 position: fixed; 27 top: 0; 28 width: 100%; 29 z-index: -1; 30 } 31 </style> 32 <body> 33 <div id="parallax-fore"></div> 34 35 36 <script type="text/javascript"> 37 38 var parallaxIt = new function(){ 39 40 var foreLayer,backLayer; 41 42 function onScroll(e){ 43 var Y = window.pageYOffset; 44 backLayer.style.backgroundPosition = " 0 -" + Y*0.6 + "px"; 45 foreLayer.style.backgroundPosition = " 0 -" + Y*0.8 + "px"; 46 } 47 48 this.init = function() { 49 foreLayer = document.getElementById("parallax-fore"); 50 backLayer = document.body; 51 window.addEventListener("scroll",onScroll); 52 }; 53 54 } 55 parallaxIt.init(); 56 </script> 57 </body> 58 </html>
咳咳,原来是没问题的,是我的错,我打开的方式不对!