如何通过JavaScript检测对contentEditable的支持?

Jas*_*son 7 html javascript cross-browser contenteditable

我一直在搜索这几天,到目前为止,我能想到的最好的是查看下面的列表.我真的不喜欢检查基于User-Agent的支持,特别是因为它可能是欺骗性的.我还听说过至少一个下面列表不正确的情况(如下所示).

  • 是Internet Explorer吗?
  • 是WebKit吗?(但我读过移动版Safari不支持它)
  • 是歌剧吗?
  • Gecko和版本> = 1.9?(意思是Firefox 3或更高版本)

是否有更好的方法基于直接通过JavaScript测试支持,或者这是测试支持的唯一方法?

bob*_*nce 9

var canEditContent= 'contentEditable' in document.body;
Run Code Online (Sandbox Code Playgroud)

  • 这在iOS 4(及更早版本)上给出了误报. (2认同)

Mik*_*scu 7

检查某个功能的最佳方法是在您知道应该支持它的元素上实际测试该功能,如下所示:

if(element.contentEditable != null)
    // then it's supported
Run Code Online (Sandbox Code Playgroud)

要么

if(typeof(element.contentEditable) != 'undefined')
   // same thing.. but with typeof you can be more specific about the type of property you need to find
Run Code Online (Sandbox Code Playgroud)

  • 这非常有用,但对于希望在iPhone/iPad上运行的人来说:定义了contentEditable属性.麻烦的是操作系统实际上并不支持它,即没有调出屏幕键盘让你输入任何内容.我在这一点上看到的唯一方法是重新编写UserAgent以解决任何与iOS相关的问题. (7认同)
  • `typeof`是一个运算符,而不是一个函数,因此不需要操作数周围的括号. (2认同)