当您使用 { background-attachment:fixed } 时,当前移动设备根本不会显示背景图片!为确保图像显示在所有移动设备上,您需要测试是否支持,如果不支持,请将 background-attachment 属性设置为“初始”(即默认状态)或“滚动”(默认状态) .
坏消息:
目前无法直接具体地测试对固定背景的支持,因为移动浏览器会错误地报告他们确实支持它。要亲自查看此错误,请在移动浏览器中加载此测试:
http://codepen.io/mattthew/pen/PwEqJa
function supportsCSS(value) {
try {
var style = document.body.style;
if (!("backgroundAttachment" in style)) return false;
var oldValue = style.backgroundAttachment;
style.backgroundAttachment = "fixed";
var isSupported = (style.backgroundAttachment === value);
style.backgroundAttachment = oldValue;
return isSupported;
}
catch (e) {
return false;
}
}
var el = document.getElementById('result');
var txt = '<b>This device & broswer supports:</b><br>';
txt += '{ background-attachment:fixed; } : ' + supportsCSS('fixed') + '<br>';
txt += { background-attachment:foo; } : ' + supportsCSS('foo');
el.innerHTML = txt;
基于最初由@chao 编写的代码
有限的选项:
可以使用多种方法间接测试支持。
选项 1:移除小屏幕上的固定背景
此选项使用 CSS 媒体查询来定位较小的屏幕,以覆盖屏幕宽度为 1024 像素或更小的设备上的样式(设备可能会将固定背景呈现为不可见)。这个选项的优点是:它非常轻量级并且只需要一点点 CSS:
#some_element {
background-attachment: fixed;
}
@media all and (max-device-width: 1024px) {
/*
overwrite property for devices with
screen width of 1024px or smaller
*/
#some_element {
background-attachment: scroll;
}
}
不幸的是,屏幕宽度为 1280px 和 1366px 的平板电脑品牌很少,与最小的桌面屏幕重叠(按 CSS 高度排序this list)。最安全的做法是对这个重叠区域使用滚动背景,以保证显示背景图像。 如果您想安全起见,请使用 max-device-width: 1366px。 但是,使用这些巨型平板电脑的人数远远少于使用小屏幕笔记本电脑的人数。
选项 2:测试触摸事件和鼠标事件
此选项使用 JS 来测试浏览器是否支持触摸事件 API,因此 更有可能在触摸屏设备上(设备更可能呈现固定背景作为隐形)。这是重量级选项。它需要Modernizr 和 jQuery:
if(Modernizr.touch) {
// this browser claims to support touch, so remove fixed background
$('#some_element').css('background-attachment','scroll');
}
很遗憾,此选项也有灰色区域。一些浏览器给出误报,一些浏览器给出误报。您可以测试鼠标事件,例如:
$('body').mousemove(function(event){
// this device (touch or not) has a mouse, so revert to fixed background
$('#some_element').css('background-attachment','fixed');
$('body').unbind('mousemove');
});
但是,鼠标可能已连接到不支持固定背景的触摸屏笔记本电脑上,因此代码会增加风险。