样式赋值处理的方式与 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的
<!doctype html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"/> <style> div { width:60px; height:60px; margin:5px; /*padding: 5px;*/ } </style> <script src="http://code.jquery.com/jquery-latest.js"></script> <title></title> </head> <body> <div id="aaron" style="background-color:yellow;">慕课网</div> <button id="test1">jQuery.css设置padding margin</button> <button id="test2">模拟style设置padding margin</button> <ul></ul> <script type="text/javascript"> ////////// //分解参数 // ////////// function access(elems, fn, key, value, chainable, emptyGet, raw) { var i = 0, len = elems.length; //如果是一个对象,for in递归调用自己 if (jQuery.type(key) === "object") { chainable = true; for (i in key) { access(elems, fn, i, key[i], true, emptyGet, raw); } } else if (value !== undefined) { if (fn) { fn(elems, key, value); } } return elems }; ////////// //设置样式 // ////////// function style(elem, name, value, extra) { var origName = jQuery.camelCase(name), style = elem.style; style[name] = value; } function css(name, value) { return access(this, function(elem, name, value) { return value !== undefined ? style(elem, name, value) : jQuery.css(elem, name); }, name, value, arguments.length > 1); } $("#test1").click(function() { $("div").css({ 'padding': '20px', 'margin': '20px' }) }) $("#test2").click(function() { css.call(document.getElementById('aaron'), { 'padding': '40px', 'margin': '40px' }) }) </script> </body> </html>