background-attachment 属性用于设置背景图像是否随页面滚动而滚动,或者固定在某个位置不动。
值
scroll:背景图像随页面滚动而滚动。fixed:背景图像固定在视口的某个位置不动。local:背景图像随元素内容滚动而滚动。
语法
background-attachment: scroll|fixed|local;
示例
// www.javascriptcn.com code example
/* 背景图像随页面滚动而滚动 */
.example1 {
background-image: url('example.jpg');
background-attachment: scroll;
}
/* 背景图像固定在视口的某个位置不动 */
.example2 {
background-image: url('example.jpg');
background-attachment: fixed;
}
/* 背景图像随元素内容滚动而滚动 */
.example3 {
background-image: url('example.jpg');
background-attachment: local;
}注意事项
- 使用
fixed值时,背景图像会固定在视口的某个位置,不会随页面滚动而滚动,适合用于创建固定背景效果。 - 在移动端开发中,建议谨慎使用
fixed值,因为固定背景图像可能会影响页面的性能和用户体验。
以上是关于 background-attachment 属性的介绍,希望能帮助你更好地掌握 CSS 样式中的背景设置。