一.如何把一个元素放在屏幕的中心位置:
view sourceprint?1 jQuery.fn.center = function () {
2 this.css('position','absolute');
3 this.css('top', ( $(window).height() - this.height() ) / +$(window).scrollTop() + 'px');
4 this.css('left', ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + 'px');
5 return this;
6 }
7 //这样来使用上面的函数:
8 $(element).center();
二.如何把有着某个特定名称的所有元素的值都放到一个数组中:
view sourceprint?1 var arrInputValues = new Array();
2 $("input[name='table[]']").each(function(){
3 arrInputValues.push($(this).val());
4 });
三.在jQuery中如何测试某个元素是否可见
view sourceprint?1 if($(element).is(':visible') == 'true') {
2 //该元素是可见的
3 }
四. 如何限制“Text-Area”域中的字符的个数:
view sourceprint?01 jQuery.fn.maxLength = function(max){
02 this.each(function(){
03 var type = this.tagName.toLowerCase();
04 var inputType = this.type? this.type.toLowerCase() : null;
05 if(type == "input" && inputType == "text" || inputType == "password"){
06 //Apply the standard maxLength
07 this.maxLength = max;
08 }
09 else if(type == "textarea"){
10 this.onkeypress = function(e){
11 var ob = e || event;
12 var keyCode = ob.keyCode;
13 var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
14 return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
15 };
16 this.onkeyup = function(){
17 if(this.value.length > max){
18 this.value = this.value.substring(0,max);
19 }
20 };
21 }
22 });
23 };
24 //用法
25 $('#mytextarea').maxLength(500);
五.如何在一段时间之后自动隐藏或关闭元素(支持1.4版本):
view sourceprint?1 //这是1.3.2中我们使用setTimeout来实现的方式
2 setTimeout(function() {
3 $('.mydiv').hide('blind', {}, 500)
4 }, 5000);
5 //而这是在1.4中可以使用delay()这一功能来实现的方式(这很像是休眠)
6 $(".mydiv").delay(5000).hide('blind', {}, 500);
六. 如何找到一个已经被选中的option元素:
view sourceprint?1 $('#someElement').find('option:selected');
七.如何获得鼠标垫光标位置x和y
view sourceprint?1 $(document).ready(function() {
2 $(document).mousemove(function(e){
3 $(’#XY’).html(”X Axis : ” + e.pageX + ” | Y Axis ” + e.pageY);
4 });
5 });
八.如何检查cookie是否启用
view sourceprint?1 var dt = new Date();
2 dt.setSeconds(dt.getSeconds() + 60);
3 document.cookie = "cookietest=1; expires=" + dt.toGMTString();
4 var cookiesEnabled = document.cookie.indexOf("cookietest=") != -1;
5 if(!cookiesEnabled) {
6 //没有启用cookie
7 }
如何让cookie过期:
view sourceprint?1 var date = new Date();
2 date.setTime(date.getTime() + (x * 60 * 1000));
3 $.cookie('example', 'foo', { expires: date });