我看了this关于如何使用JavaScript和jQuery编写真正高效的视差效果的两部分教程
当我将JS直接放入html文件时,它可以完美地工作,但是当我在外部链接它时,它不起作用。为什么?
非工作版本
(function ($) {
var $container = $(".parallax");
var $divs = $container.find("div.parallax-background");
var thingBeingScroll = document.body;
var liHeight = $divs.eq(0).closest("li").height();
var diffHeight = $divs.eq(0).height() - liHeight;
var len = $divs.length;
var i, div, li, offset, scroll, top, transform;
var offsets = $divs.get().map(function (div, d) {
return $(div).offset();
});
var render = function () {
top = thingBeingScroll.scrollTop;
for (i = 0; i < len; i++) {
div = $divs[i];
offset = top - offsets[i].top;
scroll = ~~((offset / liHeight * diffHeight) * 2);
transform = 'translate3d(0px,' + scroll + 'px,0px)';
div.style.webkitTransform = transform;
div.style.MozTransform = transform;
div.style.msTransform = transform;
div.style.OTransform = transform;
div.style.transform = transform;
}
};
(function loop() {
requestAnimationFrame(loop);
render();
})();
(function () {
var lastTime = 0;
var vendors = ['webkit', 'moz'];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function (callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function () { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function (id) {
clearTimeout(id);
};
}());
})(jQuery);
body, ul {
margin: 0;
padding: 0;
}
body {
height: 2500px;
}
ul li {
list-style: none;
overflow: hidden;
height: 600px;
}
.parallax-background {
height: 700px;
background-size: cover;
}
.lens {
background-image: url('http://www.cameraegg.org/wp-content/uploads/2013/04/sigma-art-lenses.jpg');
}
.beach {
background-image: url('https://c1.staticflickr.com/3/2422/3799310645_92dba468ae_b.jpg');
}
.wolf {
background-image: url('http://images.alphacoders.com/102/102853.jpg');
}
.flower {
background-image: url('http://i.imgur.com/Aoo6BAk.jpg');
}
<ul class="parallax">
<li>
<div class="parallax-background flower"></div>
</li>
</ul>
<h1>Content</h1>
答案 0 :(得分:1)
您的parallax.js
脚本和parallax.css
的路径似乎无效:
<script src="parallax.js" type="parallax.js"></script> <!--Parallax JS-->
<link rel="stylesheet" type="text/css" href="parallax.css"> <!--Parallax CSS-->
转到这些网址(通过点击Chrome中的链接文件),请将我发送到Google的登录页面。尝试更改脚本src并链接href以使用绝对路径,并确保两者都对公众可见。