jQuery++ 扩展 jQuery 库功能的开源插件
jQuery++ 在 jQuery 1.7.x 的基础上增加了一些新的 DOM 助手方法,目的是提供 jQuery 所不支持的功能,包括 Cookie 操作、DOM Range 和表单处理等。
这是一个开源的插件,意味着你可以免费使用,基于MIT开源协议发布。
jQuery++ 不是一个类似 jQuery UI or jQuery Tools 的插件,他只提供最基本的方法,扩展 jQuery 所不支持的功能,并且支持定制下载,去除你不需要的功能。
安装
这儿有一些可以安装 jQuery++ 的方法,你可以选择你熟悉的方式来安装 jQuery++:
- 使用下载生成器
- 下载全部文件选择性加载
- 使用 Steal 安装
- 使用 AMD 安装
使用下载生成器
官网提供了自定义下载功能,你可以选择你需要的功能,然后点击下载按钮,下载后解压你会得到一个jquerypp.custom.js
文件,这个文件是你所选功能的压缩版本,你可以通过下面的方式引入到页面中:
<script src="lib/jquery.1.8.2.js"></script><script src="lib/jquerypp.custom.js"></script>
使用AMD安装
通过AMD的方式加载 jQuery++ 插件,例如 RequireJS 工具引入插件文件,所有的文件将被下载到你的amd/
文件夹,你可以更改文件夹名称,通过下面的方式引入插件。
define(['jquery', 'jquerypp/dimensions', 'jquerypp/event/resize'],function($) {
$('#element').outerWidth(500).resize();
});
你可以需要jQuery的模块名称,在 RequireJS 如下:
require.config({paths: {
"jquery" : "http://code.jquery.com/jquery-1.8.2"
}
});
注:从1.7版本的jQuery定义本身如果装载机是为AMD模块可用。没有必要再制造一个包装器了。
特点
简单易用
jQuery++ 是基于jQuery开发的,这使得它非常容易学习,如果你已经熟悉jQuery。从一个连贯的库中实现的功能,是很难实现的:
- 序列化形式为对象的formParams
- 拖放不需要jQuery UI事件
- 调整元素的正确方式
- 监听移动应用程序
- 暂停和恢复面向事件的JavaScript应用程序事件
灵活方便
你不需要使用所有的jQuery + +。只是选择了你想使用下载生成器插件,与stealjs或AMD模块加载。每个插件只包括实际需求的依赖,所以你的JavaScript应用程序将保持尽可能小。
可授权的事件也使它很容易与 CanJS 和 Backbone 整合。没有自定义的API来照顾,只是处理事件的jQuery方法。
快速
一些jQuery++插件可以大大加快您的应用程序开发速度。使用
- compare 快速比较元件位置
- destroyed 避免内存泄露和保持你的最新参考当元素从DOM去除
参与开发
开发的jQuery++添加功能等等,你必须先安装DoneJS。DoneJS是jQuery++和JavaSciptMVC 4版本的父项目。它有DocumentJS偷作为子模块,用于生成文档并建立jQuery++下载。
安装
- 通过下面的命令克隆 DoneJS 项目到你的本地
git clone git://github.com/bitovi/donejs
- 通过运行下面的代码安装所有模块
cd donejs
git submodule update --init --recursive
根据你的Git版本,你可能需要切换到每个子模块并运行
git checkout
。 - Fork jquerypp on Github
- 添加您自己的叉子在jQuery模块中
cd jquery
git checkout master
git remote add fork git@github.com:<username>/jquerypp.git
开发
在安装 jQuery++ 和 DoneJS 以后,你可以在 jquery
文件夹找到 jQuery++ 的所有文件,在 jquery 文件夹里面,
插件文件在 dom
和 event
文件夹里面,controller
, model
, class
和 view
文件夹是当前保持向后兼容 JavaScriptMVC 3.2/3.3 不应该修改。每一个插件例如 jquery/dom/compare
你可以看到以下的文件:
compare.html
– 一个示例页面compare.js
– 实际的评论和未压缩的源代码compare.md
– 概述页面(用于生成文档)compare_test.js
– 插件测试qunit.html/funcunit.html
– 单元和功能测试
开发 jQuery++:
- 编辑插件文件
- 添加测试代码到 plugin_test.js 文件。
- 打开插件的测试页面
qunit.html
或funcunit.html
确保一切都运行不报错 - 打开
jquery/qunit.html
文件, 确保一切都运行不报错 - 提交你的xiu’g (
git push fork <branch>
) - 提交一个完整的请求
文档
编辑 jquerypp.com,安装 jQuery++ 和 DoneJS 是没有必要的。简单的fork和在线编辑GitHub的 index.md 页面, 最后别忘了点击提交。
编辑文档 DoneJS.com:
- 安装 jQuery++ 和 DoneJS。
- 编辑 markdown 和 JS 文件在
jquery
文件夹里面。 - 在
donejs
文件夹的根目录创建文件:./js site/scripts/doc.js
可以在这里看到
site/docs.html
- 提交一个完整的请求
构建
构建 jQuery++ 通过运行下面的代码:
js jquery/build/make.js
这会在 jquery/dist
文件夹创建自定义的jQuery++,建立一个特定的版本,看看你想建立和运行上述命令git tag。
DOM HELPERS
animate
$(el).animate(properties, [speed], [callback]) -> jQuery
Annotated source
jQuery.animate overwrites $.fn.animate
to use
CSS 3 animations if possible.
It takes the same arguments as the original $.fn.animate and will fall back to
jQuery’s JavaScript animation if a CSS animation is not possible.
A fade-in effect can be implemented like this:
$('#element').css({ opacity : 0
}).animate({
opacity : 1
}, 1000, function() {
console.log('Animation done');
});
Since CSS transitions are implemented natively in the browser and can make use of hardware acceleration, animations will perform a lot better, especially in Webkit based mobile browsers (iPhone, iPad, Android).
compare
$(elA).compare(elB) -> Number
Annotated source
jQuery.compare adds $.fn.compare
to compare the position of two nodes. It returns a number that represents a bitmask showing how they are positioned relative to each other. The following list shows the bitmask
, the number and what it means for a $.fn.compare
call like $('#foo').compare($('#bar'))
:
000000
-> 0: Elements are identical000001
-> 1: The nodes are in different documents (or one is outside of a document)000010
-> 2: #bar precedes #foo000100
-> 4: #foo precedes #bar001000
-> 8: #bar contains #foo010000
-> 16: #foo contains #bar
You can tell if #foo
precedes #bar
like:
if( $('#foo').compare($('#bar')) & 4 ) { console.log("#foo preceds #bar");
}
This is useful to rapidly compare element positions which is common when widgets can reorder themselves (drag-drop) or with nested widgets (trees). In the following example, select two elements to see how they compare to each other and what bitmask the result represents:
cookie
$.cookie(name, [value], [options]) -> Object|String
Annotated source
jQuery.cookie packages Klaus Hartl’s jQuery cookie plugin for manipulating cookies. Use it like:
// Set a session cookie$.cookie('the_cookie', 'the_value');
$.cookie('the_cookie'); // -> 'the_value'
// Set a cookie that expires in 7 days
$.cookie('the_cookie', 'the_value', { expires: 7 });
// delete the cookie
$.cookie('the_cookie', null);
The following options are available:
expires
– the expiration time in days or an expiry datedomain
– the domain namepath
– the value of the path for the cookiesecure
– if the cookie requires HTTPS
The example uses jQuery.cookie
and formParams to persist a form to a cookie. You can save the form
or load it from the value stored in the cookie. At the bottom it shows the current cookie value after running it through
decodeURIComponent
:
formParams
$(form).formParams([convert]) -> Object|jQuery
Annotated source
jQuery.formParams adds $.fn.formParams
which serializes a form into a JavaScript object. It creates nested objects by using bracket notation in the form element name. If convert is true
, values that look like numbers or booleans will be converted and empty strings won’t be added to the object. For a form like this:
<form> <input type="text" name="first" value="John" />
<input type="text" name="last" value="Doe" />
<input type="text" name="phone[mobile]" value="1234567890" />
<input type="text" name="phone[home]" value="0987654321" />
</form>
$.fn.formParams
returns:
$('form').formParams()// -> {
// first : "John", last : "Doe",
// phone : { mobile : "1234567890", home : "0987654321" }
// }
It is also possible to set form values by passing an object:
$('form').formParams({ first : 'Mike',
last : 'Smith'
});
Update the form in the following example to see a JSON representation of the object returned by $.fn.formParams
:
range
$.Range([el]) -> range
$(el).range() -> range
Annotated source
Use jQuery.Range to create, move and compare text ranges. Use $.Range.current()
to get the currently selected text range. $(el).range()
returns a text range on an element.
For example, for an element like <div>This is some text</div>
, $.Range
can be used like this:
// Get a text range for #textvar range = $('#text').range();
// Move the start 5 characters to the right
range.start('+5');
// Move the end 5 characters to the left
range.end('-5');
// Return the range text
range.toString(); // is some
// Select the current range
range.select();
A $.Range
instance offers the following methods:
- range.clone() -> range
– clones the range and returns a new $.Range object
- range.collapse([toStart]) -> range collapses a range
- range.compare(type, other) -> Number
– compares one range to another range
- range.end([val]) -> range|Object
– sets or returns the end of the range
- range.move(type, referenceRange) -> range
– move the endpoints of a range relative to another range
- range.overlaps(other) -> Boolean
– returns if any portion of these two ranges overlap
- range.parent() -> HtmlElement|Element|Node
– returns the most common ancestor element of the endpoints in the range
- range.rect(from) -> TextRectangle
– returns the bounding rectangle of this range
- range.rects(from) -> Array
– returns the client rects
- range.start([val]) -> range|Object
– sets or returns the beginning of the range
- range.toString() -> String
– returns the text of the range
The following example uses jQuery.range
to
- Show the start end end offset of the selection
- Show the selected plain text
- Add a green border on the left to the start element
- Add a red border on the right to the end element
- Put a dotted outline around the parent element
selection
$(el).selection([start], [end]) -> Object|jQuery
Annotated source
jQuery.selection adds $.fn.selection
to set or retrieve the currently selected text range. It works on all elements:
<div id="text">This is some text</div>
// Make a selection in #text from position eight to 12$('#text').selection(8, 12);
var selection = $('#text').selection();
// -> { start : 8, end : 12 }
$('#text').text().substring(selection.start, selection.end) // -> some
The following example shows how $.fn.selection
can be used. Initially the selection is set from position eight to 12. You can change the selection in the highlighted area and the status text will be updated:
within
$(el).within(left, top, [useOffsetCache]) -> jQuery
Annotated source
jQuery.within adds $.fn.within
and $.fn.withinBox
that return all elements having a given position or area in common. The following example returns all div
elements having the point 200px left and 200px from the top in common:
$('div').within(200, 200)
Use $(el).withinBox(left, top, width, height)
to get all elements within a certain area:
$('*').withinBox(200, 200, 100, 100)
Move the mouse in the following example and it will show the ids for div
elements within the current mouse position:
jQuery.event.drag uses jQuery.within to determine dropable elements at the current position.
EVENTS
removed
removed
Annotated source
The destroyed
event is triggered by jQuery.event.destroyed when the element is removed from the DOM using one of the jQuery manipulation methods.
$('form').on('destroyed', function() { // Clean up when a form element has been removed
});
Note: The destroyed event does not bubble.
drag
dragdown
draginit
dragmove
dragend
dragover
dragout
Annotated source
jQuery.event.drag adds delegatable drag events to jQuery:
dragdown
– the mouse cursor is pressed downdraginit
– the drag motion is starteddragmove
– the drag is moveddragend
– the drag has endeddragover
– the drag is over a drop pointdragout
– the drag moved out of a drop point
An element will become draggable by attaching an event listener for one of these events on it. A simple slider can be implemented like this:
$('#dragger').on('draginit', function(ev, drag) { drag.limit($(this).parent());
drag.horizontal();
});
Which looks like this in action:
The drag
object (passed to the event handler as the second parameter) can be used to modify the drag behavior:
- drag.cancel() -> undefined
– stops the drag motion from happening
- drag.ghost() -> jQuery
– copys the draggable and drags the cloned element
- drag.horizontal() -> drag
– limits the scroll to horizontal movement
- drag.only([only]) -> Boolean
– only have drags, no drops
- drag.representative(element, offsetX, offsetY) – move another element in place of this element
- drag.revert(val) -> drag
– animate the drag back to its position
- drag.step(pixels) -> drag
– makes the drag move in steps of amount pixels
- drag.vertical() -> drag
– limit the drag to vertical movement
- drag.limit(container, center) -> drag
– limit the drag within an element
- drag.scrolls(elements, options) -> undefined
– scroll scrollable areas when dragging near their boundaries
drop
dropinit
dropover
dropout
dropmove
dropon
dropend
Annotated source
jQuery.event.drop complements jQuery.event.drag
with delegatable drop events:
dropinit
– the drag motion is started, drop positions are calculateddropover
– a drag moves over a drop element, called once as the drop is dragged over the elementdropout
– a drag moves out of the drop elementdropmove
– a drag is moved over a drop element, called repeatedly as the element is moveddropon
– a drag is released over a drop elementdropend
– the drag motion has completed
The following example adds the highlight
class when a drag is moved over the element and removes it when it leaves:
$('.drop').on({ "dropover" : function(ev, drop, drag){
$(this).addClass('highlight');
},
"dropout" : function(ev, drop, drag){
$(this).removeClass('highlight');
}
});
The drop
object offers the following methods:
- drop.cancel() -> undefined
– prevents this drop from being dropped on
- drop.cache() -> undefined
– call on
dropinit
to cache the position of draggable elements
When adding drop-able elements after dropinit
, for example when expanding a folder view after hovering over it with a draggable for a while, $.Drop.compile() needs to be called explicitly to update the list of dropable elements (this happens automatically on dropinit
).
The following example shows two draggable elements and a drop area. When a drag starts it will create a copy of the element using drag.ghost()
. The drop area will be highlighted when the drag moves over it and update the text when it is dropped:
hover
hoverinit
hoverenter
hovermove
hoverleave
Annotated source
jQuery.event.hover provides the following hover events:
hoverinit
– called on mouseenterhoverenter
– an element is being hoveredhovermove
– the mouse moves on an element that has been hoveredhoverleave
– the mouse leaves the hovered element
$('li.menu').on({ hoverenter : function(){
$(this).addClass("hovering");
},
hoverleave : function(){
$(this).removeClass("hovering");
}
});
An element is hovered when the mouse moves less than a certain distance in a specific time over the element. These values can be modified either globally by setting $.Hover.delay
and $.Hover.distance
or individually during hoverinit
:
$(".option").on("hoverinit", function(ev, hover){ //set the distance to 10px
hover.distance(10);
//set the delay to 200ms
hover.delay(200);
})
You can also set hover.leave(time)
to set a time that the hover should stay active for after the mouse left.
The following example shows jQuery.event.hover
with different settings for distance, delay and leave:
key
event.keyName()
Annotated source
jQuery.event.key adds a .keyName()
method to the event object that returns a string representation of the current key:
$("input").on('keypress', function(ev){ // Don't allow backspace keys
if(ev.keyName() == '\b') {
ev.preventDefault();
}
if(ev.keyName() == 'f1') {
alert('I could be a tooltip for help');
}
});
The following key names are mapped by default:
\b
– backspace\t
– tab\r
– enter keyshift
,ctrl
,alt
pause-break
,caps
,escape
,num-lock
,scroll-loc
,print
page-up
,page-down
,end
,home
,left
,up
,right
,down
,insert
,delete
' '
– space0-9
– number key presseda-z
– alpha key pressednum0-9
– number pad key pressedf1-12
– function keys pressed- Symbols:
/
,;
,:
,=
,,
,-
,.
,/
,[
,\
,]
,'
,"
The following example shows the keyname for keydown
, keyup
and keypress
events on the input field:
pause
jQuery.event.pause adds a default event handler, event.pause()
and event.resume()
for pausing and resuming event propagation and $.fn.triggerAsync
for triggering an event asynchronously and executing a callback when propagation is finished.
This is very useful for creating event oriented jQuery widgets that provide default behavior for certain events.
A widget user can intercept any of these events, pause it and perform other actions before resuming the default
action or prevent it entirely.
Example
The following example implements a tabs
widget using CanJS. Each tab panel contains a form to input data. When the form data changes and you go to another tab it will ask you to save these changes before moving on. This will pause the tabs hide
event until you either confirmed or declined to save the form. On cancel the event will be prevented and the widget will stay in the current tab:
triggerAsync $(el).triggerAsync(event, [success], [prevented])
Annotated source
jQuery.fn.triggerAsync triggers an event and calls a success handler when it has finished propagating through the DOM and no handler called event.preventDefault()
or returned false
. The prevented callback will be used otherwise:
$('panel').triggerAsync('show', function(){ $('#panel').show();
},function(){
$('#other').addClass('error');
});
default events eventname.default
Annotated source
jQuery.event.default adds default event handlers. A default event runs when all other event handlers have been triggered and none has called event.preventDefault()
or returned false
. Default events are prefixed with the default
namespace. The following example adds a default toggle
event:
$('#text').on('toggle.default', function(ev) { $(this).toggle();
});
$('#text').on('toggle', function(ev, animation) {
if(animation) {
$(this).toggle(animation);
ev.preventDefault();
}
});
pause and resume event.pause()
event.resume()
Annotated source
Pausing an event works similar to .stopImmediatePropagation() by calling event.pause()
. Calling event.resume()
will continue propagation. This is great when doing asynchronous processing in an event handler:
$('#todos').on('show', function(ev){ ev.pause();
$(this).load('todos.html', function(){
ev.resume();
});
});
resize
resize
Annotated source
jQuery.event.resize allows you to listen to resize
events on arbitrary elements. Unlike other events that bubble from the target element to the document the resize
event will propagate from the outside-in.
This means that outside elements will always resize first. Trigger the resize
event whenever the dimensions of an element change and inside elements should adjust as well.
The following example will always resize to it’s full parent width and height
$('#foo').on('resize', function() { var parent = $(this).parent();
$(this).width(parent.width()).height(parent.height());
})
$(document.body).resize();
The resize
event makes creating application like layouts a lot easier. The following example creates a common layout with top, left, right and center elements within a container. Use the blue square to resize the outside container. The resize
event will take care of adjusting the dimensions of the inside elements:
swipe
swipeleft
swiperight
swipeup
swipedown
swipe
Annotated source
jQuery.event.swipe adds support for swipe motions providing the delegatableswipeleft
, swiperight
, swipedown
, swipeup
and swipe
events:
$('#swiper').on({ 'swipe' : function(ev) {
console.log('Swiping');
},
'swipeleft' : function(ev) {
console.log('Swiping left');
},
'swiperight' : function(ev) {
console.log('Swiping right');
},
'swipeup' : function(ev) {
console.log('Swiping up');
},
'swipedown' : function(ev) {
console.log('Swiping down');
}
});
Set jQuery.event.swipe.delay
to the maximum time the swipe motion is allowed to take (default is 500ms).
Swipe (using the mouse) in the green area in the following example to see the direction of the swipe。
相关链接
- Github 地址:https://github.com/bitovi/jquerypp
- 项目地址:http://jquerypp.com
以上是 jQuery++ 扩展 jQuery 库功能的开源插件 的全部内容, 来源链接: utcz.com/p/232331.html