首页
Javascript
Html
Css
Node.js
Electron
移动开发
小程序
工具类
服务端
浏览器相关
前端收藏
其他
关于
公司注册

jQuery.support源码分析(检测浏览器兼容)

2013年05月08日 发布 阅读(1419) 作者:Jerman

jquery.support主要是检测浏览器兼容性,支持力度的方法,用于展示不同浏览器各自特性和bug的属性集合。作为一个静态成员,提供给jquery内部函数,告诉他们某些功能是否能用。避免了以往通过检测浏览器版本做修改。

可以直接调用jQuery.support来检测某些功能,通过查看其源代码我们可以更深入的了解各个浏览器之间的区别。特别是针对IE,还有webkit的bug,都能让我们受益匪浅。

兼容各种主流浏览器是JavaScript库的必修课之一,一般来说检测浏览器有两种方法:

检测navigator.userAgent,用户代理检测法
检测浏览器的功能特性,即功能特性检测法
而jQuery1.3开始采用的就是功能特性检测法,以下是针对最新的jquery1.9.1版本,添加的注释。

  1. // 浏览器各自特性和bug的属性集合,功能特性检测/支持
  2. jQuery.support = (function () {
  3. // 声明变量
  4. var support, all, a,
  5. input, select, fragment,
  6. opt, eventName, isSupported, i,
  7. div = document.createElement("div");
  8. // Setup
  9. // 设置class样式
  10. div.setAttribute("className", "t");
  11. // 插入HTML
  12. div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
  13. // Support tests won't run in some limited or non-browser environments
  14. // 获取元素
  15. all = div.getElementsByTagName("*");
  16. a = div.getElementsByTagName("a")[0];
  17. // 检测是否支持最基本检测
  18. if (!all || !a || !all.length) {
  19. return {};
  20. }
  21. // First batch of tests
  22. // 创建select元素
  23. select = document.createElement("select");
  24. // 创建option元素并插入到select中
  25. opt = select.appendChild(document.createElement("option"));
  26. // 获取input元素
  27. input = div.getElementsByTagName("input")[0];
  28. // 设置CSS样式
  29. // cssText:设置样式
  30. // 说明:在IE中最后一个分号会被删掉,可以添加一个分号来解决这个问题
  31. // 例如: Element.style.cssText += ’;width:100px;height:100px;top:100px;left:100px;’
  32. a.style.cssText = "top:1px;float:left;opacity:.5";
  33. // support(支持)对象
  34. support = {
  35. // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
  36. // 验证一些属性是否支持使用get/setAttribute方法,不支持返回true,支持返回false
  37. // 通过setAttribute添加class值是否成功来检测,IE6~7支持,其他浏览器不支持
  38. getSetAttribute:div.className !== "t",
  39. // IE strips leading whitespace when .innerHTML is used
  40. // 检测节点类型是否为文本节点 成功返回true,失败返回false
  41. // 使用innerHTML,IE会自动剔除HTML代码头部的空白符
  42. leadingWhitespace:div.firstChild.nodeType === 3,
  43. // Make sure that tbody elements aren't automatically inserted
  44. // IE will insert them into empty tables
  45. // 验证是否存在tbody标签,不存在返回true,存在返回false
  46. // 确保tbody元素不会自动插入(IE6~7会自动插入的空tbody)
  47. tbody:!div.getElementsByTagName("tbody").length,
  48. // Make sure that link elements get serialized correctly by innerHTML
  49. // This requires a wrapper element in IE
  50. // 验证innerHTML插入链接元素是否可被序列化,成功则返回true,失败返回false
  51. // 所谓序列化是指:可被读取的一种存储标准,在IE6~8中返回false。
  52. htmlSerialize:!!div.getElementsByTagName("link").length,
  53. // Get the style information from getAttribute
  54. // (IE uses .cssText instead)
  55. // 验证getAttribute("style")是否返回元素的行内样式,成功返回true,失败返回false
  56. // 在IE6~8中为false,因为他用cssText代替
  57. style:/top/.test(a.getAttribute("style")),
  58. // Make sure that URLs aren't manipulated
  59. // (IE normalizes it by default)
  60. // 验证getAttribute("href")返回值是否原封不动,成功返回true,失败返回false
  61. // 在IE6~7中会返回false,因为他的URL已常规化。
  62. hrefNormalized:a.getAttribute("href") === "/a",
  63. // Make sure that element opacity exists
  64. // (IE uses filter instead)
  65. // Use a regex to work around a WebKit issue. See #5145
  66. // 验证浏览器是否能正确解析opacity,成功返回true,失败返回false
  67. // 在IE6~8中返回false,因为他用alpha滤镜代替。
  68. opacity:/^0.5/.test(a.style.opacity),
  69. // Verify style float existence
  70. // (IE uses styleFloat instead of cssFloat)
  71. // 验证cssFloat是否存在,成功返回true,失败返回false
  72. // 在IE6~8中返回false,他用styleFloat代替
  73. cssFloat:!!a.style.cssFloat,
  74. // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
  75. // 验证checkbox的默认value是否为'on',成功返回true,失败返回false
  76. // safair默认为'' 空字符串
  77. checkOn:!!input.value,
  78. // Make sure that a selected-by-default option has a working selected property.
  79. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
  80. // 验证创建的select元素的第一个option元素是否会默认选中, 成功返回true,失败返回false
  81. // FF,Chrome返回true,IE6~10返回false
  82. // 注意:option元素的父元素不一定是select,也有可能是optgroup
  83. optSelected:opt.selected,
  84. // Tests for enctype support on a form (#6743)
  85. // 验证创建form的enctype属性是否存在,存在返回true,不存在返回fasle(IE6~9,均存在)
  86. // enctype:设置表单的MIME编码,默认编码格式是application/x-www-form-urlencoded,不能用于文件上传;multipart/form-data,才能完整的传递文件数据
  87. enctype:!!document.createElement("form").enctype,
  88. // Makes sure cloning an html5 element does not cause problems
  89. // Where outerHTML is undefined, this still works
  90. // 验证是否支持html5节点复制,成功返回ture,失败返回false
  91. // 失败:复制节点cloneNode(true).innerHTML返回一个空字符串
  92. html5Clone:document.createElement("nav").cloneNode(true).outerHTML !== "<:nav></:nav>",
  93. // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
  94. // 验证页面和浏览器是否以W3C CSS盒式模型来渲染,而非怪异模式下。IE6~7的怪癖模式会返回false
  95. boxModel:document.compatMode === "CSS1Compat",
  96. // Will be defined later
  97. // 稍后将定义
  98. deleteExpando:true,
  99. noCloneEvent:true,
  100. inlineBlockNeedsLayout:false,
  101. shrinkWrapBlocks:false,
  102. reliableMarginRight:true,
  103. boxSizingReliable:true,
  104. pixelPosition:false
  105. };
  106. // Make sure checked status is properly cloned
  107. // 检测单选框选中状态能否正确克隆
  108. // 在IE6~9中会返回false,无法正确克隆
  109. // (1) 设置checkbox的checked为true
  110. input.checked = true;
  111. // (2) cloneNode克隆(复制)一份checkbox,获取他的checked值
  112. support.noCloneChecked = input.cloneNode(true).checked;
  113. // Make sure that the options inside disabled selects aren't marked as disabled
  114. // (WebKit marks them as disabled)
  115. // 检测select元素设置为disabled后,其所有option子元素是否也会被设置为disabled
  116. // (1)禁用下拉列表
  117. select.disabled = true;
  118. // (2)获取下拉列表子元素的disabled是否为true
  119. // 测试:IE FF Chrome Safair Opera 的opt.disabled都为false,说明option不会被设置为disabled
  120. // 其他:部分webkit会被设置为disabled,需要老版本的chrome支持。
  121. support.optDisabled = !opt.disabled;
  122. // Support: IE<9
  123. // 检测是否能删除附加在DOM Element 上的属性或数据
  124. // 在IE6~7中返回false,若事先声明这个属性,那么在IE8返回true,否者返回false
  125. try {
  126. delete div.test;
  127. } catch (e) {
  128. support.deleteExpando = false;
  129. }
  130. // Check if we can trust getAttribute("value")
  131. // 检测input元素被设置为radio类型后,是否仍然保持原先的值 保持成功返回true,失败返回false
  132. // 在IE6~9和opera中返回false,其他返回true
  133. input = document.createElement("input");
  134. input.setAttribute("value", "");
  135. support.input = input.getAttribute("value") === "";
  136. // Check if an input maintains its value after becoming a radio
  137. input.value = "t";
  138. input.setAttribute("type", "radio");
  139. //IE返回on
  140. support.radioValue = input.value === "t";
  141. // #11217 - WebKit loses check when the name is after the checked attribute
  142. // 先“选中”然后在“名称”,顺序要点,在老版本的chroem16和safair 下有兼容问题
  143. input.setAttribute("checked", "t");
  144. input.setAttribute("name", "t");
  145. // 创建一个文档碎片
  146. fragment = document.createDocumentFragment();
  147. // 将input元素插入到碎片中
  148. fragment.appendChild(input);
  149. // Check if a disconnected checkbox will retain its checked
  150. // value of true after appended to the DOM (IE6/7)
  151. // 检测(使用setAttribute)被添加到DOM中的checkbox是否仍然保留原先的选中状态 成功返回true,失败返回false
  152. // 在IE6~7中,返回false
  153. // 其他:(1) safair下 若先未设置"名称",返回true
  154. // 其他:(2) safair下 若设置"名称",则返回false
  155. support.appendChecked = input.checked;
  156. // WebKit doesn't clone checked state correctly in fragments
  157. // 检测fragment中的checkbox的选中状态能否被复制 成功返回true,失败返回false
  158. // 在IE6~7中 失败返回false
  159. // 其他:(1) safair下 若先设置"名称"后"选中"返回true
  160. // 其他:(2) safair下 若先设置"选中"后"名称"返回false
  161. support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked;
  162. // Support: IE<9
  163. // Opera does not clone events (and typeof div.attachEvent === undefined).
  164. // IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
  165. // 检测克隆 DOM Element 是否会连同Element一起克隆(复制),成功返回false,失败返回true
  166. // IE6~8克隆会复制事件,标准浏览器返回false
  167. // (1)IE的注册事件
  168. if (div.attachEvent) {
  169. div.attachEvent("onclick", function () {
  170. support.noCloneEvent = false;
  171. });
  172. // (2)克隆DOM Element并执行onclick事件
  173. div.cloneNode(true).click();
  174. }
  175. // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event)
  176. // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php
  177. // 检测(嗅探)事件是否支持
  178. // 其他: IE6~7不支持submitBubbles和changeBubbles,支持focusinBubbles. IE8~9均支持
  179. for (i in { submit:true, change:true, focusin:true }) {
  180. div.setAttribute(eventName = "on" + i, "t");
  181. //eventName in window 低版本iE6~7浏览器检测,返回false
  182. //高版本IE8~9浏览器检测
  183. support[i + "Bubbles"] = eventName in window || div.attributes[eventName].expando === false;
  184. }
  185. //IE9的问题,对于克隆的元素清除掉其background时,其原型的background也会被清除
  186. div.style.backgroundClip = "content-box";
  187. div.cloneNode(true).style.backgroundClip = "";
  188. // 检测原型的background是否被清除
  189. support.clearCloneStyle = div.style.backgroundClip === "content-box";
  190. // Run tests that need a body at doc ready
  191. // 页面加载完成之后开始执行
  192. jQuery(function () {
  193. var container, marginDiv, tds,
  194. // 声明保存一种样式(目的是重置样式)
  195. divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",
  196. // 获取body元素
  197. body = document.getElementsByTagName("body")[0];
  198. if (!body) {
  199. // Return for frameset docs that don't have a body
  200. // 框架的页面没有body元素,返回空值
  201. return;
  202. }
  203. // 创建DOM Element元素(div)
  204. container = document.createElement("div");
  205. // 设置 DIV 样式
  206. container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
  207. // 将DIV插入到body第一行
  208. body.appendChild(container).appendChild(div);
  209. // Support: IE8
  210. // Check if table cells still have offsetWidth/Height when they are set
  211. // to display:none and there are still other visible table cells in a
  212. // table row; if so, offsetWidth/Height are not reliable for use when
  213. // determining if an element has been hidden directly using
  214. // display:none (it is still safe to use offsets if a parent element is
  215. // hidden; don safety goggles and see bug #4512 for more information).
  216. // 插入table表格
  217. div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
  218. // 获取TD
  219. tds = div.getElementsByTagName("td");
  220. // 检测none状态下,offsetHeight值是否正确,正确返回true,失败返回false
  221. // 在IE6~8下返回false
  222. // (1)设置TD[0]样式
  223. tds[0].style.cssText = "padding:0;margin:0;border:0;display:none";
  224. // (2)检测TD[0]的内容高度是否为0
  225. isSupported = (tds[0].offsetHeight === 0);
  226. // 检测TD初始化,相邻的td的隐藏,offsetHeight值是否正确,正确返回true,失败返回false
  227. // 在IE6~8返回false
  228. // 设置TD[0]display(显示)初始化,相邻的td隐藏
  229. tds[0].style.display = "";
  230. tds[1].style.display = "none";
  231. // Support: IE8
  232. // Check if empty table cells still have offsetWidth/Height
  233. support.reliableHiddenOffsets = isSupported && (tds[0].offsetHeight === 0);
  234. // Check box-sizing and margin behavior
  235. // 清理div子元素
  236. div.innerHTML = "";
  237. // 设置盒模型以及margin等行为
  238. div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
  239. // 检测是否符盒模型(通过offsetWidth来判断)
  240. // 在IE6~7中返回false 返回值为6
  241. support.boxSizing = (div.offsetWidth === 4);
  242. // 字面翻译:body偏移不是因为margin影响 (未验证)
  243. support.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== 1);
  244. // Use window.getComputedStyle because jsdom on node.js will break without it.
  245. // 未来判断(向上检测)
  246. // 判断是否支持getComputedStyle方法
  247. // getComputedStyle:获取当前元素所有最终使用的CSS属性值,返回的是一个CSS样式声明对象
  248. if (window.getComputedStyle) {
  249. // 检测图层定位(像素位置)是否有误,正确返回false 错误返回true
  250. support.pixelPosition = (window.getComputedStyle(div, null) || {}).top !== "1%";
  251. // 检测盒模型是否可靠
  252. support.boxSizingReliable = (window.getComputedStyle(div, null) || { width:"4px" }).width === "4px";
  253. // Check if div with explicit width and no margin-right incorrectly
  254. // gets computed margin-right based on width of container. (#3333)
  255. // Fails in WebKit before Feb 2011 nightlies
  256. // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
  257. // 为处理某个BUG存在,块级元素margin right兼容问题
  258. // webkit 返回错误的值
  259. // 创建一个div元素
  260. marginDiv = div.appendChild(document.createElement("div"));
  261. // 样式声明或(重置)
  262. marginDiv.style.cssText = div.style.cssText = divReset;
  263. marginDiv.style.marginRight = marginDiv.style.width = "0";
  264. div.style.width = "1px";
  265. support.reliableMarginRight =
  266. !parseFloat((window.getComputedStyle(marginDiv, null) || {}).marginRight);
  267. }
  268. // FF不支持zoom 检测IE6~7 版本
  269. if (typeof div.style.zoom !== core_strundefined) {
  270. // Support: IE<8
  271. // Check if natively block-level elements act like inline-block
  272. // elements when setting their display to 'inline' and giving
  273. // them layout
  274. div.innerHTML = "";
  275. div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
  276. // 检测IE6~7下,块元素在display:inline并拥有layout属性,是否会按inline-block显示
  277. support.inlineBlockNeedsLayout = (div.offsetWidth === 3);
  278. // Support: IE6
  279. // Check if elements with layout shrink-wrap their children
  280. // 检测父元素拥有layout属性和固定的width/height,是否会被子元素撑大。成功返回true失败,返回false
  281. // 在IE6中返回true,(值是7)
  282. div.style.display = "block";
  283. div.innerHTML = "<div></div>";
  284. div.firstChild.style.width = "5px";
  285. support.shrinkWrapBlocks = (div.offsetWidth !== 3);
  286. if (support.inlineBlockNeedsLayout) {
  287. // Prevent IE 6 from affecting layout for positioned elements #11048
  288. // Prevent IE from shrinking the body in IE 7 mode #12869
  289. // Support: IE<8
  290. body.style.zoom = 1;
  291. }
  292. }
  293. // 移除container元素 垃圾回收,避免内存泄露
  294. body.removeChild(container);
  295. // Null elements to avoid leaks in IE
  296. container = div = tds = marginDiv = null;
  297. });
  298. // IE下,创建DOM Element对象,如果没有append到页面中,刷新页面,这部分内存是不会回收的
  299. // 不需要的DOM Element,需要做结束清理
  300. // 释放dom元素占用的内存
  301. // 释放DOM Element对象,垃圾清理,内存回收
  302. // Null elements to avoid leaks in IE
  303. all = select = fragment = opt = a = input = null;
  304. // 返回结果
  305. return support;
  306. })();
版权声明:本站文章除特别声明外,均采用署名-非商业性使用-禁止演绎 4.0 国际 许可协议,如需转载,请注明出处
  • jQuery对象中类数组的概念及操作

    什么是类数组?相信我们对function方法的arguments很熟悉,arguments就像一个数组,但instanceof Array检测会返回false,可以称为“类数组”。

    发布:2014-04-10 阅读(1523)

  • jquery使用不当导致内存泄漏

    jQuery是现在最流行的js库,一般情况下我们都会放心的使用它,不用考虑其内存泄漏的问题。 最近的项目是基于MVC模式的管理系统,期间要采用ajax不断轮询服务器,以获得最新的数据,这时候使用jQuery的时候就要注意了,一不小心俺们最可爱的IE内存就up up up了~~

    发布:2013-12-10 阅读(1780)

  • jQuery.support源码分析(检测浏览器兼容)

    jquery.support主要是检测浏览器兼容性,支持力度的方法,用于展示不同浏览器各自特性和bug的属性集合。作为一个静态成员,提供给jquery内部函数,告诉他们某些功能是否能用。避免了以往通过检测浏览器版本做修改。

    发布:2013-05-08 阅读(1419)

  • jQuery跳出each循环(替换break,continue)

    jQuery each循环中,如果要实现类似break或continue的功能,不用跟原生javascript for循环一样用break或continue了,而必须用reaturn false、return true

    发布:2012-11-14 阅读(1703)