我编写了一个小脚本,通过页面滚动使照片背景同时向上滚动/按钮。问题是页面滚动后背景图像滚动(有延迟)。
问题:如何通过页面滚动来移动背景图像,例如http://shapebootstrap.net/item/1524936-unika-responsive-one-page-html5-template/live-demo?
我用我的代码制作了一个plnkr:https://plnkr.co/edit/e6OCUF4sXSA80Pi6XANj?p=preview
var bgScroll = function(lastScrollTop, elem) {
lastScrollTop = $(window).scrollTop();
$(elem).css('transition', 'all .5s');
$(elem).css('background-position', '0% ' + parseInt(-lastScrollTop / 2) + 'px');
console.log('lastScrollTop = ' + lastScrollTop);
};
$(window).load(function() {
var lastST = 0;
var homeElem = '#add-outer-container';
$(window).on("scroll", function() {
bgScroll(lastST, homeElem);
});
});
html,
body {
height: 100%;
margin: 0;
padding: 0;
background-color: gray;
}
#add-outer-container {
width: 100%;
height: 500px;
background: #fff url(http://www.gettyimages.pt/gi-resources/images/Homepage/Hero/PT/PT_hero_42_153645159.jpg) no-repeat fixed 0% 0%;
overflow: hidden;
color: white;
border: 1px solid red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- version 0.6.1.0 -->
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="app.js"></script>
<link rel="stylesheet" type="text/css" href="app.css"></link>
</head>
<body>
<div id="add-outer-container"></div>
<div style="height: 1500px; color: green;"></div>
</body>
</html>
答案 0 :(得分:2)
您正在寻找的是视差效果。有几个库可以帮助您(例如http://pixelcog.github.io/parallax.js/)。但最简单的解决方案可能是这样的:
// Handle the window scroll event
$(window).scroll(function () {
// Store the distance scrolled
var scrolled = $(window).scrollTop() + 1;
// Set the scroll speed
var scrollSpeed = 0.3;
// Update the background position
$("#add-outer-container").css('background-position', '0' + -(scrolled * scrollSpeed) + 'px');
});
&#13;
body {
min-height:3000px;
}
#add-outer-container {
background:url(http://www.gettyimages.pt/gi-resources/images/Homepage/Hero/PT/PT_hero_42_153645159.jpg) no-repeat fixed;
width:100%;
height:500px;
margin:0 auto;
border: 1px solid red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="add-outer-container"></div>
&#13;
答案 1 :(得分:0)
1-删除行:$(elem).css('transition', 'all .5s');
你的CSS中的2-添加到#add-outer-container class:
transition: all 0.5s;
transition-timing-function:cubic-bezier(0,0,0.2,1);