检测后台附件支持:修复?

Mal*_*001 17 javascript css jquery modernizr

有没有办法检测浏览器对后台附件的支持:修复?

编辑:虽然桌面浏览器广泛支持此功能,但它在便携式设备上的支持很差,我希望能够检测到该功能.

mat*_*hew 7

当您使用{background-attachment:fixed}时,当前的移动设备根本不会显示背景图像!要确保图像显示在所有移动设备上,您需要测试支持,如果不支持将后台附件属性设置为"初始"(即默认状态)或"滚动"(这是默认状态) .

 

坏消息:

目前无法直接和专门测试固定背景的支持,因为移动浏览器会错误地报告他们确实支持它.要自己查看此错误,请在移动浏览器中加载此测试:

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 &amp; broswer supports:</b><br>';
txt += '{ background-attachment:fixed; } : ' + supportsCSS('fixed') + '<br>';
txt +=  { background-attachment:foo; } : ' + supportsCSS('foo');

el.innerHTML = txt;
Run Code Online (Sandbox Code Playgroud)

基于最初编写的代码:@chao


有限的选择:

可以使用多种方法间接测试支持.

选项1:在小屏幕上删除固定背景

此选项使用CSS媒体查询来定位较小的屏幕,以覆盖屏幕宽度为1024px或更小的设备上的样式(可能将固定背景渲染为不可见的设备).这个选项的优点是:它非常轻量级,只需要一点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;
     }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,有少量平板电脑品牌的屏幕宽度为1280像素和1366像素,与最小的桌面屏幕重叠(按CSS高度排序此列表).最安全的游戏是为此重叠区域使用滚动背景,以确保显示背景图像. 如果您想安全地使用它,请使用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');
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这个选项也有灰色区域.有些浏览器会出现误报,有些会给出误报.您可以测试鼠标事件,例如:

$('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');
});
Run Code Online (Sandbox Code Playgroud)

但是,鼠标可能已连接到不支持固定背景的触摸屏笔记本电脑,因此代码会增加风险.


Cod*_*ner -4

http://www.w3schools.com/cssref/pr_background-attachment.asp

页面下方有主要浏览器图标的图片。任何图标的图像都不会变灰。它说所有浏览器都支持它

  • 您引用的网站声称 IE 不支持“@font-face”,尽管发明了该规则。 (5认同)
  • @CodyGuldner:他的意思是,你不能真正相信 w3schools 对此类事情的说法。他们因拥有过时的、有时甚至是完全错误的信息而臭名昭著。您必须自己确定,此时网站上的内容并不特别重要。 (2认同)