这是固定的内容
这是一些文本内容。
以下是一个使用CSS和JavaScript实现背景滚动而内容固定不动的示例:
HTML代码:
这是固定的内容
这是一些文本内容。
CSS代码:
.background {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: auto;
background-image: url(背景图片的URL);
background-repeat: repeat-y;
background-attachment: fixed;
}
.content {
width: 600px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
}
JavaScript代码:
window.addEventListener('scroll', function() {
var background = document.querySelector('.background');
var content = document.querySelector('.content');
var scrollPosition = window.pageYOffset;
background.style.backgroundPositionY = -scrollPosition + 'px';
content.style.transform = 'translateY(' + scrollPosition + 'px)';
});
请将代码中的背景图片的URL
替换为你要使用的图片的URL。这段代码将使用position: fixed
将整个背景元素固定在窗口中,然后使用background-attachment: fixed
将背景图片固定在背景元素上。通过监听窗口的滚动事件,我们可以实现当用户滚动时改变背景元素的background-position-y
属性,并使用transform
属性将内容元素向上或向下平移相同的距离,从而实现背景滚动而内容固定不动的效果。
上一篇:背景滚动效果时底部位置不正确
下一篇:背景过渡效果无法正常工作