极湖

无不用其“极”

Subscribe to RSS feed

Posts tagged with "jQuery"

用 jQuery 写代码的几种固定模式

,

1. 基本模式
$(document).ready(function(){
    // 自己的代码
});


2. 常用模式
$(function(){
    // 自己的代码
});


3. 和其他框架共用模式
jQuery(document).ready(function($){
    // 自己的代码
});


4. 2和3的组合模式
jQuery(function($){
    // 自己的代码
});



参考: http://5509.me/log/jquery-execution-pattern

用 jQuery 做简单的弹出对话框

,

用 jQuery 做一个简单的弹出对话框 用 jQuery 做了一个简单的弹出对话框,可用于智能手机。
// 让元素居中的函数
jQuery.fn.center = function () {
    $win = $(window);
    this.css('position','absolute');
    this.css('top', (($win.height() - this.outerHeight()) / 2) + $win.scrollTop() + 'px');
    this.css('left', (($win.width() - this.outerWidth()) / 2) + $win.scrollLeft() + 'px');
    return this;
}

// 弹出对话框函数
jQuery.msgBox = function(sMsg, sTitle, sButton) {
    sMsg = sMsg || '';
    sTitle = sTitle || '消息';
    sButton = sButton || '关闭';
    $alertBox = $('<div>').css({
        'position': 'absolute',
        'top': '0',
        'left': '0',
        'width': '300px',
        'height': '150px',
        'border-radius': '5px',
        'padding': '2px',
        'background': '#000',
        'color': '#FFF',
        'opacity': '0.8',
        'z-index': '999',
        'text-align': 'center'
    }).append('<div style="background:#333;border-radius:3px;padding:2px;margin:4px;font-size:90%;">' + sTitle + '</div>')
        .append('<div style="height:70px;margin:8px;2px;text-align:left;">' + sMsg + '</div>')
        .append($('<button style="padding:3px;">' + sButton + '</button>').click(function(e) {
            $alertBox.remove();
        })
    ).prependTo(document.body).center().show();
};

//测试(示例)
$('#test').click(function(){
    $.msgBox('Hello world!');
});

解决 Android 浏览器页面内跳转问题

, ,

Android 的浏览器(可能仅限于某些版本),如果URL本身带有 #top 这样的字符串,页面内的跳转(anchor)将不起作用。
为此,用 javascript 解决如下:
$("a[href^=#]").click(function(e) {
    //if(window.location.href.indexOf('#') == -1) return true;  // 仅对应 URL 带 # 的情况
    e.preventDefault();
    var sAnchor = $(this).attr('href').replace('#', '');
    var $target = $('a[name=' + sAnchor + ']').next();
    var nTop = ($target.length > 0) ? $target.offset().top : 0;
    $(window).scrollTop(nTop);
    // 若需动画效果
    //$(document.body).animate({ scrollTop: nTop }, 'slow');
    return false;
});

注:以上代码基于 jQuery。

JavaScript: 控制滚动条使某一元素可见

,

方法一(原理):
document.getElementById('youridhere').scrollIntoView();

方法二:
用 jQuery 的插件 jQuery.ScrollTo 来实现
$(...).scrollTo( 0, 800, {queue:true} );


参考:http://stackoverflow.com/questions/68165/javascript-to-scroll-long-page-to-div

发送 Ajax 请求时显示"加载中..."的方法(jQuery)

,

发送 Ajax 请求的时候,最好有个“加载中...”的显示,要不然有时候用户会认为没有响应。jQuery 可通过 ajaxSetup 轻松实现这一功能,代码如下:
$(document).ready(function() {
    $loadMask = $('<div><img src="/images/ajax-loader.gif" /><br>加载中...</div>');
    $loadMask.css({
        'position': 'absolute',
        'top': '0',
        'left': '0',
        'width': '280px',
        'height': '65px',
        'border-radius': '5px',
        'padding-top': '20px',
        'background': '#000',
        'color': '#FFF',
        'opacity': '0.8',
        'z-index': '999',
        'text-align': 'center',
        'font-size': '150%'
    }).prependTo(document.body).hide();
    $.ajaxSetup({
        timeout: 30000, // 超时设置:5分钟
        beforeSend: function(){
            $win = $(window);
            var x = (($win.width() - $loadMask.outerWidth()) / 2) + $win.scrollLeft() + "px";
            var y = (($win.height() - $loadMask.outerHeight()) / 2) + $win.scrollTop() + "px";
            $loadMask.css({
                left: x,
                top: y
            }).show();
        },
        complete: function(){
            $loadMask.hide();
        }
    });
});

让元素在屏幕中央显示的 jQuery 函数

,

以下代码可让元素在屏幕中央显示,无论网页是否滚动。
jQuery.fn.center = function () {
    $win = $(window);
    this.css('position','absolute');
    this.css('top', (($win.height() - this.outerHeight()) / 2) + $win.scrollTop() + 'px');
    this.css('left', (($win.width() - this.outerWidth()) / 2) + $win.scrollLeft() + 'px');
    return this;
}


用法举例如下:

HTML代码:
<img id="test" src="http://www.google.co.jp/images/nav_logo83.png" />

JS 代码:
$('#test').center();


jQuery 取 select 列表值的方法

很简单,一句话
$('#selectList :selected').attr('value');

注意不能用 $('#selectList').val();

压缩后只有 4kb 的迷你 jQuery

, ,

因为想做 iPhone 的 Web 应用,这些天一直在找一个轻量的 javascript 库。

今天终于找到一个可用的:
http://www.freelancephp.net/light-4kb-mini-jquery/

这个库仅实现了 jQuery 的一部分功能,且限于 DOM 操作,不过目前对我来说已经足够。

这个库的代码非常简单易懂,因此很容易扩展。为了实现更多的 jQuery 基本功能,我追加了几个函数:
hasClass, hide, show, html, text, val, find

我追加的代码如下:
	// determine className
	hasClass: function ( className ) {
		for ( var i = 0; i < this.els.length; i++ ) {
			if(this.els[i].className.match(new RegExp('\\b' + className + '\\b')))
				return true;
		}
		return false;
	},

	// hide elements
	hide: function () {
		this.each(function( el ) {
			el.style.display = 'none';
		});
		return this;
	},

	// show elements
	show: function () {
		this.each(function( el ) {
			el.style.display = 'block';
		});
		return this;
	},

	// set inner html
	html: function (value) {
		if(value == undefined) {
			return this.els[0] ? this.els[0].innerHTML : '';
		}
		this.each(function( el ) {
			el.innerHTML = value;
		});

		return this;
	},

	// set inner text
	text: function (value) {
		var name = (document.body.textContent != undefined) ? 'textContent' : 'innerText';
		if(value == undefined) {
			return this.els[0] ? this.els[0][name] : '';
		}
		this.each(function( el ) {
			el[name] = value;
		});

		return this;
	},

	// set value
	val: function (value) {
		if(value == undefined) {
			return this.els[0] ? this.els[0].value : '';
		}
		this.each(function( el ) {
			el.value = value;
		});

		return this;
	},

	// find children
	find: function (selector) {
		return new this.init( selector, this.get(0) );
	},

修改后的文件:
light.js
light.min.js

这个库的选择器部分,仅仅是 getEmelentById, getElementsByName 的简单扩展。如果需要用到类似 $("td:eq(2)") 甚至更复杂的选择器,就得另想办法了。幸运的是,这个库提供了接口,你可以采用以下的选择器代码:
Sizzle, Sly, NWMatcher, Peppy, Yass

方法很简单:
Light.selector = Sly; // use Sly  engine
Light.selector = Sizzle; // use Sizzle engine
Light.selector = NW.Dom.select; // use NWMatcher engine
Light.selector = peppy.query; // use Peppy engine
Light.selector = _; // use YASS engine

jQuery 选择器练习题:数字拼图

,

题目: 4*4格式的数字表格,鼠标点击某个数字,移动到相邻空白处。 我用 jQuery 实现如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>移动数字</title>
<style type="text/css">
#grid {
	margin-top: 0.2em;
	margin-bottom: 1em;
	border-collapse: separate;
	border-spacing: 2px;
	font-size: 26px;
}
#grid td {
	border-bottom: solid 1px #B2B2B2;
	border-right: solid 1px #B2B2B2;
	background: #F3F3F3;
	text-align: center;
	white-space: nowrap;
	cursor: pointer;
	padding: 4px;
	width: 30px;
	empty-cells: show;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
	var sHtml = '<tr>';
	var MAX = 16;
	for(var i=1; i<=MAX; i++) {
		if(i < MAX) {
			sHtml += '<td>' + i + '</td>';
			if(i % 4 == 0) {
				sHtml += '</tr><tr>';
			}
		} else {
			sHtml += '<td></td>';
			sHtml += '</tr>';
		}
	}
	$('#grid').html(sHtml);
	$('#grid td').click(function(e){
		$td = $(this);
		var idx = $td.prevAll().length;
		var $left = $td.prev();
		var $right = $td.next();
		var $above = $td.parent().prev().children('td:eq(' + idx + ')');
		var $below = $td.parent().next().children('td:eq(' + idx + ')');
		var $target = null;
		if($left && $left.html() == '') {
			$target = $left;
		} else if($right && $right.html() == '') {
			$target = $right;
		} else if($above && $above.html() == '') {
			$target = $above;
		} else if($below && $below.html() == '') {
			$target = $below;
		}
		if($target) {
			$target.html($td.html());
			$td.html('');
		}
	});
});
</script>
</head>
<body>
<center>
<table id="grid">
</table>
</center>
</body>
</html>

IME 打开时 Firefox 不触发 keyup 之解决方法

, ,

输入法打开时, Firefox 不触发 keyup 事件。经常写javascript代码的人,尤其是中日韩等国的人,都可能会遇上这个不大好解决的问题,。

在一个日文 Blog 上找到了解决办法,用 jQuery 通过 text 事件实现。
自己写了一段测试代码如下:

var logFunc = function(e){
  console.log($(this).val());
  if(e){
    // keyup 时能取到键值
    console.log(e.keyCode)
  }
};
$(':text').keyup(logFunc).text('text', logFunc);
February 2012
S M T W T F S
January 2012March 2012
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29