4-4 样式的赋值
本节编程练习不计算学习进度,请电脑登录imooc.com操作

样式的赋值

样式赋值处理的方式与 css 类似,只是要注意了 style 才具有样式的修改权限,这样的传对象其实都是需要调用多次 style 处理的,当然没有采用 cssText 的方式处理,因为本身以前的属性就会丢失了,值得注意的是,设置样式的时候我们是可以传递一个对象为参数的:

$div.css({
    'padding' : '50',
    'margin'  : '50'
})

可以一次让元素添加多个属性,那么因为我们内部没有采用 cssText 去处理,而是靠的 style 接口,那么意味着就需要针对 jQuery 的参数去修正,换句话说我们就需要通过for in或者each去遍历这个参数,分解出每一个属性赋值给 style 接口。针对参数的多形式 jquery 在之前会通过一个 jQuery.access 方法过滤这些参数,原理就是针对字符串、数组、对象的一个遍历而已。

jQuery的处理流程:

1. 分解参数
2. 转换为驼峰式,修正属性名
3. 如果有钩子,则调用钩子的set get
4. 最终实现都是依靠浏览器自己的API的

 

 

任务

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
  5. <style>
  6. div {
  7. width:60px;
  8. height:60px;
  9. margin:5px;
  10. /*padding: 5px;*/
  11. }
  12. </style>
  13. <script src="http://code.jquery.com/jquery-latest.js"></script>
  14. <title></title>
  15. </head>
  16. <body>
  17.  
  18. <div id="aaron" style="background-color:yellow;">慕课网</div>
  19.  
  20. <button id="test1">jQuery.css设置padding margin</button>
  21. <button id="test2">模拟style设置padding margin</button>
  22.  
  23. <ul></ul>
  24.  
  25. <script type="text/javascript">
  26.  
  27.  
  28.  
  29. //////////
  30. //分解参数 //
  31. //////////
  32. function access(elems, fn, key, value, chainable, emptyGet, raw) {
  33. var i = 0,
  34. len = elems.length;
  35. //如果是一个对象,for in递归调用自己
  36. if (jQuery.type(key) === "object") {
  37. chainable = true;
  38. for (i in key) {
  39. access(elems, fn, i, key[i], true, emptyGet, raw);
  40. }
  41. } else if (value !== undefined) {
  42. if (fn) {
  43. fn(elems, key, value);
  44. }
  45. }
  46. return elems
  47. };
  48.  
  49.  
  50. //////////
  51. //设置样式 //
  52. //////////
  53. function style(elem, name, value, extra) {
  54. var origName = jQuery.camelCase(name),
  55. style = elem.style;
  56. style[name] = value;
  57. }
  58.  
  59. function css(name, value) {
  60. return access(this, function(elem, name, value) {
  61. return value !== undefined ?
  62. style(elem, name, value) :
  63. jQuery.css(elem, name);
  64. }, name, value, arguments.length > 1);
  65. }
  66.  
  67.  
  68. $("#test1").click(function() {
  69. $("div").css({
  70. 'padding': '20px',
  71. 'margin': '20px'
  72. })
  73. })
  74.  
  75. $("#test2").click(function() {
  76. css.call(document.getElementById('aaron'), {
  77. 'padding': '40px',
  78. 'margin': '40px'
  79. })
  80. })
  81.  
  82.  
  83.  
  84.  
  85.  
  86. </script>
  87. </body>
  88. </html>
下一节