话不多说,上代码
<script>
function isInViewport(node) {
var rect = node.getBoundingClientRect()
return (
(rect.height > 0 || rect.width > 0) &&
rect.bottom >= 0 &&
rect.right >= 0 &&
rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.left <= (window.innerWidth || document.documentElement.clientWidth)
)
}
$(window).scroll(function() {
var scrollTop = $(window).scrollTop();
var scrolled = $(window).scrollTop()
$('.bg').each(function(index, element) { //此处添加需实现模块的背景图类名
console.log(111)
var initY = $(this).offset().top
var height = $(this).height()
var endY = initY + $(this).height()
// Check if the element is in the viewport.
var visible = isInViewport(this)
if(visible) {
var diff = scrolled - initY
var ratio = Math.round((diff / height) * 100)
$(this).css('background-position','center ' + parseInt(-(ratio * -2)) + 'px')
}
});
})
</script>