jQuery 和 Zepto 的一些差异
虽然 Zepto.js 和 jQuery 的很多 API 相同,但一些 API 细节上差异很大。
下面就实际使用中遇到的做一下列举( 查看演示 )。
$(htmlString, attributes)
DOM 操作区别
(function($) { $(function() { var $list = $('<ul><li>jQuery 插入</li></ul>', { id: 'insert-by-jquery' }); $list.appendTo($('body')); }); })(window.jQuery);
jQuery 操作 ul
上的 id
不会被添加。
Zepto(function($) { var $list = $('<ul><li>Zepto 插入</li></ul>', { id: 'insert-by-zepto' }); $list.appendTo($('body')); });
Zepto 可以在 ul
上添加 id
。
事件触发区别
(function($) { $(function() { $script = $('<script />', { src: 'http://cdn.amazeui.org/amazeui/1.0.1/js/amazeui.min.js', id: 'ui-jquery' }); $script.appendTo($('body')); $script.on('load', function() { console.log('jQ script loaded'); }); }); })(window.jQuery);
使用 jQuery 时 load
事件的处理函数 不会 执行。
Zepto(function($) { $script = $('<script />', { src: 'http://cdn.amazeui.org/amazeui/1.0.1/js/amazeui.js', id: 'ui-zepto' }); $script.appendTo($('body')); $script.on('load', function() { console.log('zepto script loaded'); }); });
使用 Zepto 时 load
事件的处理函数 会 执行。
width()
/ height()
- Zepto.js: 由盒模型(
box-sizing
)决定 - jQery: 忽略盒模型,始终返回内容区域的宽/高(不包含
padding
、border
)
jQuery 官方的说明 :
Note that .width()
will always return the content width, regardless of the value of the CSS box-sizing
property. As of jQuery 1.8, this may require retrieving the CSS width plus box-sizing
property and then subtracting any potential border and padding on each element when the element has box-sizing: border-box
. To avoid this penalty, use .css("width")
rather than .width()
.
解决方式就是使用 .css('width')
而不是 .width()
。
边框三角形宽高的获取
假设用下面的 HTML 和 CSS 画了一个小三角形:
<div class="caret"></div>
.caret { width: 0; height: 0; border-width: 0 20px 20px; border-color: transparent transparent blue; border-style: none dotted solid; }
- jQuery 使用
.width()
和.css('width')
都返回 ,高度也一样; - Zepto 使用
.width()
返回 ,使用.css('width')
返回0px
。
所以,这种场景,jQuery 使用 .outerWidth()
/ .outerHeight()
;Zepto 使用 .width()
/ .height()
。
offset()
- Zepto.js: 返回
top
、left
、width
、height
- jQuery: 返回
width
、height
隐藏元素
- Zepto.js: 无法获取宽高;
- jQuery: 可以获取。
随着 jQuery 2.x 的发布以及未来 3.0 对浏览器支持的划分,似乎找不到再使用 Zepto 的理由了。如果你真在乎文件大小,那你可以自行打包 jQuery 中需要的模块。这和 Zepto 是一样的,Zepto 官方提供的版本只打包了很基础的模块。