【发布时间】:2015-02-13 21:35:17
【问题描述】:
我有一个 gif 用于背景,并在页面首次加载时居中。当我开始滚动网站时,gif 会移动到最左边,并且永远不会再次居中。我在想我缺少一种可以在滚动时保持背景固定的 CSS 样式。也可能是我的 jQuery 视差函数不断将其推向左侧。
下面是我正在使用的代码
//html
<section class="box slide slide-1">
<div class="container">
<!-- <h1>Main Title</h1> -->
</div>
</section>
//css
section.box.slide {
padding: 240px 0;
background-position: 0 0;
/* background-position: center;*/
}
section.box.slide h1 {
color: yellow;
font-size: 48px;
/*line-height: 1;*/
font-weight: 700;
text-align: center;
text-transform: uppercase;
text-shadow: 0 0 10px black;
}
section.box.slide-1 {
border: 1px solid white;
background: #D80000 url("../gif/lRoomWhiteRed.gif") no-repeat;
background-position: center;
/* background-attachment: fixed;*/
/* background-size: cover*/
}
//用于视差的jQuery
(function(){
var parallax = document.querySelectorAll(".slide"),
speed = .3;
window.onscroll = function(){
[].slice.call(parallax).forEach(function(p,i){
var windowYOffset = window.pageYOffset,
theBackgroundPos = "0 " + (windowYOffset * speed) + "px";
p.style.backgroundPosition = theBackgroundPos;
});
};
})();
【问题讨论】:
-
我会假设它是你的视差......
-
视差偏移了窗口上的 Y,这就是为什么这让我感到困惑,因为我认为偏移中心我必须偏移页面上的 X。也许增加 theBackgroundPos= "0" + windowYoffset 中的 0 ??
-
好的,这是视差 - 将 0 值更改为居中,并将滚动图像居中 - 是否可以将 jQuery 更改为仅在第一个背景而不是其他背景中居中滚动?
标签: jquery css background scroll center