你知道一些核心 jQuery 函数都有自己的“插件API”称为“钩子”?
jQuery 提供一个 API 来调用用户自定义的函数,用于扩展,以便获取和设置特定属性值。在 .attr,.prop(),.val()和 .css()的操作中都会引入钩子,钩子都有相似的结构。
var someHook = {
get: function(elem) {
// obtain and return a value
return "something";
},
set: function(elem, value) {
// do something with value
}
}
钩子用来干什么?
在做 css3 属性浏览器兼容的时候,都需要特定的前缀。
Webkit 内核浏览器:-webkit-border-radius Firefox 内核浏览器:-moz-border-radius
此时我看可以采用一个CSS hook 可以标准化这些供应商前缀的属性,让 css 接受一个单一的标准的属性的名称(border-radius 或用 DOM 属性的语法 borderRadius)判断的代码省略,直接看实现,给某一元素设置borderRadius 为10px。
$("#element").css("borderRadius", "10px");
为了做浏览器兼容,我们不得不:
if(webkit){
........................
}else if(firefox){
...........................
}else if(...)更多
这是一种最没技术含量的写法了,如果我们换成一种 hook 的话:
$.cssHooks.borderRadius = {
get: function( elem, computed, extra ) {
return $.css( elem, borderRadius );
},
set: function( elem, value) {
elem.style[ borderRadius ] = value;
}
};
$.cssHooks 对象提供了一种方法通过定义函数来获取和设置特定的CSS值的方法,它也可以被用来创建新的 cssHooks 以标准化 CSS3 功能,如框阴影和渐变。
例如 border-radius 属性,在早起的时候还没有形成标准化浏览器都有各自的实现,比如基于 webkit 的谷歌浏览器就需要写成 webkit-border-radius,Firefox 就需要写成 -moz-border-radius ,所以我们需要一个钩子都判断这个标准实现这个头部的前缀添加。
除了提供了对特定样式的处理可以采用更加细致的控制外,$.cssHooks也扩展了 .animate() 方法上可用的属性。这里可能还不能直观的体现,我们需在之后章节中深入到 css 源码中看到具体的用法。如果浏览器不支持任何形式的 CSS 属性写法,并且也不支持任何前缀写法,那么该样式是不会应用到元素上的。但是,如果浏览器支持某种特殊的写法,那么可以在 cssHooks 中添加对该特殊用法的支持。
<!doctype html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"/> <script src="http://code.jquery.com/jquery-latest.js"></script> <style> div { width:60px; height:60px; margin:5px; float:left; } </style> <title>样式操作</title> </head> <body> <div id="a1" style="background-color:blue;"></div> <div id="a2" style="background-color:rgb(15,99,30);"></div> <button id="test1">标准驼峰写法设置</button> <button id="test2">自定义属性名字设置</button> <script type="text/javascript"> $.cssHooks.aaronBorderRadius = { get: function(elem, computed, extra) { return $.css(elem, 'borderRadius'); }, set: function(elem, value) { elem.style['borderRadius'] = value; } }; $('#test1').click(function() { $("#a1").css("borderRadius", "10px"); }) $('#test2').click(function() { $("#a2").css("aaronBorderRadius", "20px"); }) </script> </body> </html>