2009年4月11日星期六
用jQuery制作模拟下拉框
1,浏览器自带的 下拉框样式不好看。
2,在ie6下,下拉框的优先级大于层,经常导致下拉框显示在层的上面。
OK,明白这个问题后,我们就开始用jQuery制作模拟下拉框。
先构建HTML结构和CSS样式。
看Demo1:
http://cssrain.cn/demo/jqueryCRselectbox/demo1.html
构建好后,我们开始添加效果。
看Demo2:
http://cssrain.cn/demo/jqueryCRselectbox/demo2.html
好,有了前2个例子的基础,我们完全可以构建一个插件:
看Demo3:
http://cssrain.cn/demo/jqueryCRselectbox/demo3.html
思路:
通过已知的下拉框,把里面的数据循环出来,放到另一个div的ul列表里,
另一个div就是简单的弹出层而已。
通过hidden可以 获取下拉框的选中的值和文本 。
源文件下载:
http://cssrain.cn/demo/jqueryCRselectbox/jqueryCRselectbox.rar
JSLint: The JavaScript Verifier
What is JSLint?
JSLint is a JavaScript program that looks for problems in JavaScript programs.
When C was a young programming language, there were several common programming errors that were not caught by the primitive compilers, so an accessory program called lint was developed which would scan a source file, looking for problems.
As the language matured, the definition of the language was strengthened to eliminate some insecurities, and compilers got better at issuing warnings. lint is no longer needed.
JavaScript is a young-for-its-age language. It was originally intended to do small tasks in webpages, tasks for which Java was too heavy and clumsy. But JavaScript is a very capable language, and it is now being used in larger projects. Many of the features that were intended to make the language easy to use are troublesome for larger projects. A lint for JavaScript is needed: JSLint, a JavaScript syntax checker and validator.
JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems.
JSLint defines a professional subset of JavaScript, a stricter language than that defined by Edition 3 of the ECMAScript Language Specification. The subset is related to recommendations found in Code Conventions for the JavaScript Programming Language.
JavaScript is a sloppy language, but inside it there is an elegant, better language. JSLint helps you to program in that better language and to avoid most of the slop.
JSLint can operate on JavaScript source, HTML source, or JSON text.
Undefined Variables and Functions
JavaScript's biggest problem is its dependence on global variables, particularly implied global variables. If a variable is not explicitly declared (usually with the var statement), then JavaScript assumes that the variable was global. This can mask misspelled names and other problems.
JSLint expects that all variables and functions are declared before they are used or invoked. This allows it to detect implied global variables. It is also good practice because it makes programs easier to read.
Sometimes a file is dependent on global variables and functions that are defined elsewhere. You can identify these to JSLint by including a comment in your file that lists the global functions and objects that your program depends on, but that are not defined in your program or script file.
A global declaration can look like this:
/*global getElementByAttribute, breakCycles, hanoi */
A global declaration starts with /*global. Notice that there is no space before the g. You can have as many /*global comments as you like. They must appear before the use of the variables they specify.
Some globals can be predefined for you. Select the Assume a browser (browser) option (see Options below) to predefine the standard global properties that are supplied by web browsers, such as window and document and alert. Select the Assume Rhino (rhino) option to predefine the global properties provided by the Rhino environment. Select the Assume a Yahoo Widget (widget) option to predefine the global properties provided by the Yahoo! Widgets environment.
Members
Since JavaScript is a loosely-typed, dynamic-object language, it is not possible to determine at compile time if property names are spelled correctly. JSLint provides some assistance with this.
At the bottom of its report, JSLint displays a /*members*/ comment. It contains all of the names and string literals that were used with dot notation, subscript notation, and object literals to name the members of objects. You can look through the list for misspellings. Member names that were only used once are shown in italics. This is to make misspellings easier to spot.
You can copy the /*members*/ comment into your script file. JSLint will check the spelling of all property names against the list. That way, you can have JSLint look for misspellings for you.
Semicolon
JavaScript uses a C-like syntax which requires the use of semicolons to delimit statements. JavaScript attempts to make semicolons optional with a semicolon insertion mechanism. This is dangerous.
Like C, JavaScript has ++ and -- and ( operators which can be prefixes or suffixes. The disambiguation is done by the semicolon.
In JavaScript, a linefeed can be whitespace or it can act as a semicolon. This replaces one ambiguity with another.
JSLint expects that every statement be followed by ; except for for, function, if, switch, try, and while. JSLint does not expect to see unnecessary semicolons or the empty statement.
Line Breaking
As a further defense against the semicolon insertion mechanism, JSLint expects long statements to be broken only after one of these punctuation characters or operators:
, . ; : { } ( [ = < > ? ! + - * / % ~ ^ | &
== != <= >= += -= *= /= %= ^= |= &= << >> || &&
=== !== <<= >>= >>> >>>=
JSLint does not expect to see a long statement broken after an identifier, a string, a number, closer, or a suffix operator:
) ] ++ --
JSLint allows you to turn on the Tolerate sloppy line breaking (laxbreak) option.
Semicolon insertion can mask copy/paste errors. If you always break lines after operators, then JSLint can do better at finding them.
Comma
The comma operator can lead to excessively tricky expressions. It can also mask some programming errors.
JSLint expects to see the comma used as a separator, but not as an operator (except in the initialization and incrementation parts of the for statement). It does not expect to see elided elements in array literals. Extra commas should not be used. A comma should not appear after the last element of an array literal or object literal because it can be misinterpreted by some browsers.
Required Blocks
JSLint expects that if and for statements will be made with blocks {that is, with statements enclosed in braces}.
JavaScript allows an if to be written like this:
if (condition)
statement;
That form is known to contribute to mistakes in projects where many programmers are working on the same code. That is why JSLint expects the use of a block:
if (condition) {
statements;
}
Experience shows that this form is more resilient.
Forbidden Blocks
In many languages, a block introduces a scope. Variables introduced in a block are not visible outside of the block.
In JavaScript, blocks do not introduce a scope. There is only function-scope. A variable introduced anywhere in a function is visible everywhere in the function. JavaScript's blocks confuse experienced programmers and lead to errors because the familiar syntax makes a false promise.
JSLint expects blocks with function, if, switch, while, for, do, and try statements and nowhere else. An exception is made for an unblocked if statement on an else or for in.
Expression Statements
An expression statement is expected to be an assignment or a function/method call or delete. All other expression statements are considered to be errors.
for in
The for in statement allows for looping through the names of all of the properties of an object. Unfortunately, it also loops through all of the members which were inherited through the prototype chain. This has the bad side effect of serving up method functions when the interest is in data members.
The body of every for in statement should be wrapped in an if statement that does filtering. It can select for a particular type or range of values, or it can exclude functions, or it can exclude properties from the prototype. For example,
for (name in object) {
if (object.hasOwnProperty(name)) {
....
}
}
switch
A common error in switch statements is to forget to place a break statement after each case, resulting in unintended fall-through. JSLint expects that the statement before the next case or default is one of these: break, return, or throw.
var
JavaScript allows var definitions to occur anywhere within a function. JSLint is more strict.
JSLint expects that a var will be declared only once, and that it will be declared before it is used.
JSLint expects that a function will be declared before it is used.
JSLint expects that parameters will not also be declared as vars.
JSLint does not expect the arguments array to be declared as a var.
JSLint does not expect that a var will be defined in a block. This is because JavaScript blocks do not have block scope. This can have unexpected consequences. Define all variables at the top of the function.
with
The with statement was intended to provide a shorthand in accessing members in deeply nested objects. Unfortunately, it behaves very badly when setting new members. Never use the with statement. Use a var instead.
JSLint does not expect to see a with statement.
=
JSLint does not expect to see an assignment statement in the condition part of an if or for or while or do statement. This is because it is more likely that
if (a = b) {
...
}
was intended to be
if (a == b) {
...
}
If you really intend an assignment, wrap it in another set of parens:
if ((a = b)) {
...
}
== and !=
The == and != operators do type coercion before comparing. This is bad because it causes ' \t\r\n' == 0 to be true. This can mask type errors.
When comparing to any of the following values, use the === or !== operators, which do not do type coercion.
0 '' undefined null false true
If you want the type coercion, then use the short form. Instead of
(foo != 0)
just say
(foo)
and instead of
(foo == 0)
say
(!foo)
The === and !== operators are preferred. There is a Disallow == and != (eqeqeq) option which requires the use of === and !== in all cases.
Labels
JavaScript allows any statement to have a label, and labels have a separate name space. JSLint is more strict.
JSLint expects labels only on statements that interact with break: switch, while, do, and for. JSLint expects that labels will be distinct from vars and parameters.
Unreachable Code
JSLint expects that a return, break, continue, or throw statement will be followed by a } or case or default.
Confusing Pluses and Minuses
JSLint expects that + will not be followed by + or ++, and that - will not be followed by - or --. A misplaced space can turn + + into ++, an error that is difficult to see. Use parens to avoid confusion..
++ and --
The ++ (increment) and -- (decrement) operators have been known to contribute to bad code by encouraging excessive trickiness. They are second only to faulty architecture in enabling to viruses and other security menaces. There is an option that prohibits the use of these operators.
Bitwise Operators
JavaScript does not have an integer type, but it does have bitwise operators. The bitwise operators convert their operands from floating point to integers and back, so they are not near as efficient as in C or other languages. They are rarely useful in browser applications. The similarity to the logical operators can mask some programming errors. There is an option that prohibits the use of these operators.
eval is evil
The eval function (and its relatives, Function, setTimeout, and setInterval) provide access to the JavaScript compiler. This is sometimes necessary, but in most cases it indicates the presence of extremely bad coding. The eval function is the most misused feature of JavaScript.
void
In most C-like languages, void is a type. In JavaScript, void is a prefix operator that always returns undefined. JSLint does not expect to see void because it is confusing and not very useful.
Regular Expressions
Regular expressions are written in a terse and cryptic notation. JSLint looks for problems that may cause portability problems. It also attempts to resolve visual ambiguities by recommending explicit escapement.
JavaScript's syntax for regular expression literals overloads the / character. To avoid ambiguity, JSLint expects that the character preceding a regular expression literal is a ( or = or : or , character.
Constructors and new
Constructors are functions that are designed to be used with the new prefix. The new prefix creates a new object based on the function's prototype, and binds that object to the function's implied this parameter. If you neglect to use the new prefix, no new object will be made and this will be bound to the global object. This is a serious mistake.
JSLint enforces the convention that constructor functions be given names with initial uppercase. JSLint does not expect to see a function invocation with an initial uppercase name unless it has the new prefix. JSLint does not expect to see the new prefix used with functions whose names do not start with initial uppercase. This can be controlled with an option.
JSLint does not expect to see the wrapper forms new Number, new String, new Boolean.
JSLint does not expect to see new Object (use {} instead).
JSLint does not expect to see new Array (use [] instead).
Unsafe Characters
There are characters that are handled inconsistently in the various implementations, and so must be escaped when placed in strings.
\u0000-\u001f
\u007f-\u009f
\u00ad
\u0600-\u0604
\u070f
\u17b4
\u17b5
\u200c-\u200f
\u2028-\u202f
\u2060-\u206f
\ufeff
\ufff0-\uffff
Not Looked For
JSLint does not do flow analysis to determine that variables are assigned values before used. This is because variables are given a value (undefined) which is a reasonable default for many applications.
JSLint does not do any kind of global analysis. It does not attempt to determine that functions used with new are really constructors (except by enforcing capitalization conventions), or that method names are spelled correctly.
HTML
JSLint is able to handle HTML text. It can inspect the JavaScript content contained within <script>...</script> tags. It also inspects the HTML content, looking for problems that are known to interfere with JavaScript:
- All tag names must be in lower case.
- All tags that can take a close tag (such as </p>) must have a close tag.
- All tags are correctly nested.
- The entity < must be used for literal '<'.
JSLint is less anal than the sycophantic conformity demanded by XHTML, but more strict than the popular browsers.
JSLint also checks for the occurrence of '</' in string literals. You should always write '<\/' instead. The extra backslash is ignored by the JavaScript compiler but not by the HTML parser. Tricks like this should not be necessary, and yet they are.
There is an option that allows use of upper case tagnames. There is also an option that allows the use of inline HTML event handlers.
CSS
JSLint can inspect CSS files. It expects the first line of a CSS file to be
@charset "UTF-8";
This feature is experimental. Please report any problems or limitations.
There is an option that will tolerate some of the non-standard-but-customary
workarounds.
Report
If JSLint is able to complete its scan, it generates a function report. It lists for each function:
- The line number on which it starts.
- Its name. In the case of anonymous functions, JSLint will "guess" the name.
- The parameters.
- Closure: The variables and parameters that are declared in the function that are used by its inner functions.
- Variables: The variables that are declared in the function that are used only by the function.
- Unused: The variables that are declared in the function that are not used. This may be an indication of an error.
- Outer: Variables used by this function that are declared in another function.
- Global: Global variables that are used by this function.
- Label: Statement labels that are used by this function.
The report will also include a list of all of the member names that were used. There is a list of JSLint messages.
| adsafe | true if ADsafe.org rules widget pattern should be enforced. |
| bitwise | true if bitwise operators should not be allowed |
| browser | true if the standard browser globals should be predefined |
| cap | true if upper case HTML should be allowed |
| newcap | true if Initial Caps must be used with constructor functions |
| css | true if CSS workarounds should be tolerated |
| debug | true if debugger statements should be allowed |
| eqeqeq | true if === should be required |
| evil | true if eval should be allowed |
| forin | true if unfiltered for in statements should be allowed |
| fragment | true if HTML fragments should be allowed |
| immed | true if immediate function invocations must be wrapped in parens |
| indent | the number of spaces used for indentation (default is 4) |
| laxbreak | true if statement breaks should not be checked |
| nomen | true if names should be checked for initial underbars |
| on | true if HTML event handlers should be allowed |
| onevar | true if only one var statement per function should be allowed |
| passfail | true if the scan should stop on first error |
| plusplus | true if ++ and -- should not be allowed |
| predef | an array of strings, the names of predefined global variables |
| regexp | true if . should not be allowed in RegExp literals |
| rhino | true if the Rhino environment globals should be predefined |
| safe | true if the safe subset rules are enforced. These rules are used by ADsafe. |
| sidebar | true if the Windows Sidebar Gadgets globals should be predefined |
| strict | true if the ES3.1 "use strict"; pragma is required. |
| sub | true if subscript notation may be used for expressions better expressed in dot notation |
| undef | true if undefined global variables are errors |
| white | true if strict whitespace rules apply |
| widget | true if the Yahoo Widgets globals should be predefined |
Options
The implementation of JSLint accepts an option object that allows you to determine the subset of JavaScript that is acceptable to you. It is also possible to set those options within the source of a script.
An option specification can look like this:
/*jslint nomen: true, debug: true,
evil: false, onevar: true */
An option specification starts with /*jslint. Notice that there is no space before the j. The specification contains a sequence of name value pairs, where the names are JSLint options, and the values are true or false. An option specification takes precedence over the option object.
Feedback
Please let me know if JSLint is useful for you. Is it too strict? Is there a check or a report that could speed up your debugging? douglas@crockford.com
I intend to continue to adapt JSLint based on your comments. Keep watching for improvements. Updates are announced at http://tech.groups.yahoo.com/group/jslint_com/.
Try it
Try it. Paste your script into the window and click the button. The analysis is done by a script running on your machine. Your script is not sent over the network.
It is also available as a Konfabulator widget. You can check a file by dragging it and dropping it on the widget. You can recheck the file by double-clicking the widget.
It is also available in a WSH Command Line version.
It is also available in a Rhino Command Line version.
Warning!
JSLint will hurt your feelings.
Implementation
JSLint uses a Pratt Parser (Top Down Operator Precedence). It is written in JavaScript. The full source code is available:
js验证表单大全
<script>
function test()
{
if(document.a.b.value.length>50)
{
alert("不能超过50个字符!");
document.a.b.focus();
return false;
}
}
</script>
<form name=a onsubmit="return test()">
<textarea name="b" cols="40" wrap="VIRTUAL" rows="6"></textarea>
<input type="submit" name="Submit" value="check">
</form>
2. 只能是汉字
<input onkeyup="value="/oblog/value.replace(/[^\u4E00-\u9FA5]/g,'')">
3." 只能是英文
<script language=javascript>
function onlyEng()
{
if(!(event.keyCode>=65&&event.keyCode<=90))
event.returnvalue=false;
}
</script>
<input onkeydown="onlyEng();">
4. 只能是数字
<script language=javascript>
function onlyNum()
{
if(!((event.keyCode>=48&&event.keyCode<=57)||(event.keyCode>=96&&event.keyCode<=105)))
//考虑小键盘上的数字键
event.returnvalue=false;
}
</script>
<input onkeydown="onlyNum();">
5. 只能是英文字符和数字
<input onkeyup="value="/oblog/value.replace(/[\W]/g,"'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))">
6. 验证油箱格式
<SCRIPT LANGUAGE=javascript RUNAT=Server>
function isEmail(strEmail) {
if (strEmail.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
return true;
else
alert("oh");
}
</SCRIPT>
<input type=text onblur=isEmail(this.value)>
7. 屏蔽关键字(这里屏蔽***和****)
<script language="javascript1.2">
function test() {
if((a.b.value.indexOf ("***") == 0)||(a.b.value.indexOf ("****") == 0)){
alert(":)");
a.b.focus();
return false;}
}
</script>
<form name=a onsubmit="return test()">
<input type=text name=b>
<input type="submit" name="Submit" value="check">
</form>
8. 两次输入密码是否相同
<FORM METHOD=POST ACTION="">
<input type="password" id="input1">
<input type="password" id="input2">
<input type="button" value="test" onclick="check()">
</FORM>
<script>
function check()
{
with(document.all){
if(input1.value!=input2.value)
{
alert("false")
input1.value = "";
input2.value = "";
}
else document.forms[0].submit();
}
}
</script>
够了吧 :)
屏蔽右键 很酷
oncontextmenu="return false" ondragstart="return false" onselectstart="return false"
加在body中
二
2.1 表单项不能为空
<script language="javascript">
<!--
function CheckForm()
{
if (document.form.name.value.length == 0) {
alert("请输入您姓名!");
document.form.name.focus();
return false;
}
return true;
}
-->
</script>
2.2 比较两个表单项的值是否相同
<script language="javascript">
<!--
function CheckForm()
if (document.form.PWD.value != document.form.PWD_Again.value) {
alert("您两次输入的密码不一样!请重新输入.");
document.ADDUser.PWD.focus();
return false;
}
return true;
}
-->
</script>
2.3 表单项只能为数字和"_",用于电话/银行帐号验证上,可扩展到域名注册等
<script language="javascript">
<!--
function isNumber(String)
{
var Letters = "1234567890-"; //可以自己增加可输入值
var i;
var c;
if(String.charAt( 0 )=='-')
return false;
if( String.charAt( String.length - 1 ) == '-' )
return false;
for( i = 0; i < String.length; i ++ )
{
c = String.charAt( i );
if (Letters.indexOf( c ) < 0)
return false;
}
return true;
}
function CheckForm()
{
if(! isNumber(document.form.TEL.value)) {
alert("您的电话号码不合法!");
document.form.TEL.focus();
return false;
}
return true;
}
-->
</script>
2.4 表单项输入数值/长度限定
<script language="javascript">
<!--
function CheckForm()
{
if (document.form.count.value > 100 || document.form.count.value < 1)
{
alert("输入数值不能小于零大于100!");
document.form.count.focus();
return false;
}
if (document.form.MESSAGE.value.length<10)
{
alert("输入文字小于10!");
document.form.MESSAGE.focus();
return false;
}
return true;
}
//-->
</script>
2.5 中文/英文/数字/邮件地址合法性判断
<SCRIPT LANGUAGE="javascript">
<!--
function isEnglish(name) //英文值检测
{
if(name.length == 0)
return false;
for(i = 0; i < name.length; i++) {
if(name.charCodeAt(i) > 128)
return false;
}
return true;
}
function isChinese(name) //中文值检测
{
if(name.length == 0)
return false;
for(i = 0; i < name.length; i++) {
if(name.charCodeAt(i) > 128)
return true;
}
return false;
}
function isMail(name) // E-mail值检测
{
if(! isEnglish(name))
return false;
i = name.indexOf(" at ");
j = name dot lastIndexOf(" at ");
if(i == -1)
return false;
if(i != j)
return false;
if(i == name dot length)
return false;
return true;
}
function isNumber(name) //数值检测
{
if(name.length == 0)
return false;
for(i = 0; i < name.length; i++) {
if(name.charAt(i) < "0" || name.charAt(i) > "9")
return false;
}
return true;
}
function CheckForm()
{
if(! isMail(form.Email.value)) {
alert("您的电子邮件不合法!");
form.Email.focus();
return false;
}
if(! isEnglish(form.name.value)) {
alert("英文名不合法!");
form.name.focus();
return false;
}
if(! isChinese(form.cnname.value)) {
alert("中文名不合法!");
form.cnname.focus();
return false;
}
if(! isNumber(form.PublicZipCode.value)) {
alert("邮政编码不合法!");
form.PublicZipCode.focus();
return false;
}
return true;
}
//-->
</SCRIPT>
2.6 限定表单项不能输入的字符
<script language="javascript">
<!--
function contain(str,charset)// 字符串包含测试函数
{
var i;
for(i=0;i<charset.length;i++)
if(str.indexOf(charset.charAt(i))>=0)
return true;
return false;
}
function CheckForm()
{
if ((contain(document.form.NAME.value, "%\(\)><")) || (contain(document.form.MESSAGE.value, "%\(\)><")))
{
alert("输入了非法字符");
document.form.NAME.focus();
return false;
}
return true;
}
//-->
</script>
1. 检查一段字符串是否全由数字组成
---------------------------------------
<script language="Javascript"><!--
function checkNum(str){return str.match(/\D/)==null}
alert(checkNum("1232142141"))
alert(checkNum("123214214a1"))
// --></script>
2. 怎么判断是否是字符
---------------------------------------
if (/[^\x00-\xff]/g.test(s)) alert("含有汉字");
else alert("全是字符");
3. 怎么判断是否含有汉字
---------------------------------------
if (escape(str).indexOf("%u")!=-1) alert("含有汉字");
else alert("全是字符");
4. 邮箱格式验证
---------------------------------------
//函数名:chkemail
//功能介绍:检查是否为Email Address
//参数说明:要检查的字符串
//返回值:0:不是 1:是
function chkemail(a)
{ var i=a.length;
var temp = a.indexOf('@');
var tempd = a.indexOf('.');
if (temp > 1) {
if ((i-temp) > 3){
if ((i-tempd)>0){
return 1;
}
}
}
return 0;
}
5. 数字格式验证
---------------------------------------
//函数名:fucCheckNUM
//功能介绍:检查是否为数字
//参数说明:要检查的数字
//返回值:1为是数字,0为不是数字
function fucCheckNUM(NUM)
{
var i,j,strTemp;
strTemp="0123456789";
if ( NUM.length== 0)
return 0
for (i=0;i<NUM.length;i++)
{
j=strTemp.indexOf(NUM.charAt(i));
if (j==-1)
{
//说明有字符不是数字
return 0;
}
}
//说明是数字
return 1;
}
6. 电话号码格式验证
---------------------------------------
//函数名:fucCheckTEL
//功能介绍:检查是否为电话号码
//参数说明:要检查的字符串
//返回值:1为是合法,0为不合法
function fucCheckTEL(TEL)
{
var i,j,strTemp;
strTemp="0123456789-()# ";
for (i=0;i<TEL.length;i++)
{
j=strTemp.indexOf(TEL.charAt(i));
if (j==-1)
{
//说明有字符不合法
return 0;
}
}
//说明合法
return 1;
}
7. 判断输入是否为中文的函数
---------------------------------------
function ischinese(s){
var ret=true;
for(var i=0;i<s.length;i++)
ret=ret && (s.charCodeAt(i)>=10000);
return ret;
}
8. 综合的判断用户输入的合法性的函数
---------------------------------------
<script language="javascript">
//限制输入字符的位数开始
//m是用户输入,n是要限制的位数
function issmall(m,n)
{
if ((m<n) && (m>0))
{
return(false);
}
else
{return(true);}
}
9. 判断密码是否输入一致
---------------------------------------
function issame(str1,str2)
{
if (str1==str2)
{return(true);}
else
{return(false);}
}
10. 判断用户名是否为数字字母下滑线
---------------------------------------
function notchinese(str){
var reg=/[^A-Za-z0-9_]/g
if (reg.test(str)){
return (false);
}else{
return(true); }
}
11. form文本域的通用校验函数
---------------------------------------
作用:检测所有必须非空的input文本,比如姓名,账号,邮件地址等等。
该校验现在只针对文本域,如果要针对form里面的其他域对象,可以改变判断条件。
使用方法:在要检测的文本域中加入title文字。文字是在提示信息,你要提示给用户的该字段的中文名。比如要检测用户名
html如下<input name="txt_1" title="姓名">,当然,最好用可视化工具比如dreamweaver什么的来编辑域。
如果要检测数字类型数据的话,再把域的id统一为sz.
javascript判断日期类型比较麻烦,所以就没有做日期类型校验的程序了.高手可以补充。
程序比较草,只是提供一个思路。抛砖引玉! :)
哦,对了,函数调用方法:< form onsubmit="return dovalidate()">
function dovalidate()
{
fm=document.forms[0] //只检测一个form,如果是多个可以改变判断条件
for(i=0;i<fm.length;i++)
{
//检测判断条件,根据类型不同可以修改
if(fm[i].tagName.toUpperCase()=="INPUT" &&fm[i].type.toUpperCase()=="TEXT" && (fm[i].title!=""))
if(fm[i].value="/blog/="")//
{
str_warn1=fm[i].title+"不能为空!";
alert(str_warn1);
fm[i].focus();
return false;
}
if(fm[i].id.toUpperCase()=="SZ")//数字校验
{
if(isNaN(fm[i].value))
{ str_warn2=fm[i].title+"格式不对";
alert(str_warn2);
fm[i].focus();
return false;
}
}
}
return true;
}
2 >表单提交验证类
2.1 表单项不能为空
<script language="javascript">
<!--
function CheckForm()
{
if (document.form.name.value.length == 0) {
alert("请输入您姓名!");
document.form.name.focus();
return false;
}
return true;
}
-->
</script>
2.2 比较两个表单项的值是否相同
<script language="javascript">
<!--
function CheckForm()
if (document.form.PWD.value != document.form.PWD_Again.value) {
alert("您两次输入的密码不一样!请重新输入.");
document.ADDUser.PWD.focus();
return false;
}
return true;
}
-->
</script>
2.3 表单项只能为数字和"_",用于电话/银行帐号验证上,可扩展到域名注册等
<script language="javascript">
<!--
function isNumber(String)
{
var Letters = "1234567890-"; //可以自己增加可输入值
var i;
var c;
if(String.charAt( 0 )=='-')
return false;
if( String.charAt( String.length - 1 ) == '-' )
return false;
for( i = 0; i < String.length; i ++ )
{
c = String.charAt( i );
if (Letters.indexOf( c ) < 0)
return false;
}
return true;
}
function CheckForm()
{
if(! isNumber(document.form.TEL.value)) {
alert("您的电话号码不合法!");
document.form.TEL.focus();
return false;
}
return true;
}
-->
</script>
2.4 表单项输入数值/长度限定
<script language="javascript">
<!--
function CheckForm()
{
if (document.form.count.value > 100 || document.form.count.value < 1)
{
alert("输入数值不能小于零大于100!");
document.form.count.focus();
return false;
}
if (document.form.MESSAGE.value.length<10)
{
alert("输入文字小于10!");
document.form.MESSAGE.focus();
return false;
}
return true;
}
//-->
</script>
2.5 中文/英文/数字/邮件地址合法性判断
<SCRIPT LANGUAGE="javascript">
<!--
function isEnglish(name) //英文值检测
{
if(name.length == 0)
return false;
for(i = 0; i < name.length; i++) {
if(name.charCodeAt(i) > 128)
return false;
}
return true;
}
function isChinese(name) //中文值检测
{
if(name.length == 0)
return false;
for(i = 0; i < name.length; i++) {
if(name.charCodeAt(i) > 128)
return true;
}
return false;
}
function isMail(name) // E-mail值检测
{
if(! isEnglish(name))
return false;
i = name.indexOf(" at ");
j = name dot lastIndexOf(" at ");
if(i == -1)
return false;
if(i != j)
return false;
if(i == name dot length)
return false;
return true;
}
function isNumber(name) //数值检测
{
if(name.length == 0)
return false;
for(i = 0; i < name.length; i++) {
if(name.charAt(i) < "0" || name.charAt(i) > "9")
return false;
}
return true;
}
function CheckForm()
{
if(! isMail(form.Email.value)) {
alert("您的电子邮件不合法!");
form.Email.focus();
return false;
}
if(! isEnglish(form.name.value)) {
alert("英文名不合法!");
form.name.focus();
return false;
}
if(! isChinese(form.cnname.value)) {
alert("中文名不合法!");
form.cnname.focus();
return false;
}
if(! isNumber(form.PublicZipCode.value)) {
alert("邮政编码不合法!");
form.PublicZipCode.focus();
return false;
}
return true;
}
//-->
</SCRIPT>
2.6 限定表单项不能输入的字符
<script language="javascript">
<!--
function contain(str,charset)// 字符串包含测试函数
{
var i;
for(i=0;i<charset.length;i++)
if(str.indexOf(charset.charAt(i))>=0)
return true;
return false;
}
function CheckForm()
{
if ((contain(document.form.NAME.value, "%\(\)><")) || (contain(document.form.MESSAGE.value, "%\(\)><")))
{
alert("输入了非法字符");
document.form.NAME.focus();
return false;
}
return true;
}
//-->
</script>
jQuery中文入门指南,翻译加实例,jQuery的起点教程
中文版译者:Keel
此文以实例为基础一步步说明了jQuery的工作方式。现以中文翻译(添加我的补充说明)如下。如有相关意见或建议请 EMAIL 告知。或者在 BLOG中留言。
英文原版:http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery ,感谢原文作者 Jörn Zaefferer
本文发布已征求原作者同意。
说明:在本教程发布之后,得到了几个网友的指正,对部分内容作了修正,但在jQuery版本不断更新的情况下,教程中的某些内容已经过时(尤其是1.3以上版本),在忠于原文的基础上,我将这部分内容加以标红的补充说明,希望更多的前端开发者能对此文提出宝贵意见,谢谢! --2009-3-10
另外我认为在学习过程中,有两个API文档你要打开随时查看:
- http://api.jquery.com/ [注:已更新为jquery新地址]
- http://visualjquery.com/
以下部分为原文翻译:
jQuery入门指南教程
这个指南是一个对jQuery库的说明,要求读者了解HTML(DOM)和CSS的一些常识。它包括了一个简单的Hello World的例子,选择器和事件基础,AJAX、FX的用法,以及如何制作jQuery的插件。 这个指南包括了很多代码,你可以copy它们,并试着修改它们,看看产生的效果。
内容提要
安装
一开始,我们需要一个jQuery的库,最新的下载可以到这里找到。这个指南提供一个基本包含实例的包供下载.
(译者Keel注:一定要下载这个包,光看文章不实践肯定是不行的。)
下载后解压缩,然后用你最喜欢的文本编辑器打开starterkit.html和custom.js这两个文件。(译者Keel注:这两个就是例子文件,所有的例子都用这两个例子作出,custom.js写jQuery代码,starterkit.html观察效果.建议用editPlus打开)
现在,我们就已经做好了一切准备来进行这个著名的"Hello world"例子.
本章的相关链接:
Hello jQuery
在做所有事情之前,我们要让jQuery读取和处理文档的DOM,必须尽可能快地在DOM载入后开始执行事件,所以,我们用一个ready事件作为处理HTML文档的开始.看看我们打开的custom.js这个文件,里面已经准备好了:
$(document).ready(function() {
// do stuff when DOM is ready
});
放一个简单的alert事件在需要等DOM完成载入,所以我们把任务稍稍变复杂一点:在点击任何一个链接时显示一个alert.
$(document).ready(function() {
$("a").click(function() {
alert("Hello world!");
});
});
这样在你点击页面的一个链接时都会触发这个"Hello world"的提示。
(译者Keel注:请照此代码修改custom.js并保存,然后用浏览器打开starterkit.html观察效果。)
让我们看一下这些修改是什么含义。$("a") 是一个jQuery选择器(selector),在这里,它选择所有的a标签(译者Keel注:即<a></a>),$号是 jQuery “类”(jQuery "class")的一个别称,因此$()构造了一个新的jQuery 对象(jQuery object)。函数 click() 是这个jQuery对象的一个方法,它绑定了一个单击事件到所有选中的标签(这里是所有的a标签),并在事件触发时执行了它所提供的alert方法.
这里有一个拟行相似功能的代码:
<a href="#" onclick="alert('Hello world')">Link</a>
不同之处很明显,用jQuery不需要在每个a标签上写onclick事件,所以我们拥有了一个整洁的结构文档(HTML)和一个行为文档(JS),达到了将结构与行为分开的目的,就像我们使用CSS追求的一样.
下面我们会更多地了解到选择器与事件.
本章的相关链接:
Find me:使用选择器和事件
jQuery提供两种方式来选择html的elements,第一种是用CSS和Xpath选择器联合起来形成一个字符串来传送到jQuery的构造器(如:$("div > ul a"));第二种是用jQuery对象的几个methods(方法)。这两种方式还可以联合起来混合使用。
为了测试一下这些选择器,我们来试着在我们starterkit.html中选择并修改第一个ordered list.
一开始,我们需要选择这个list本身,这个list有一个ID叫“orderedlist”,通常的javascript写法是document.getElementById("orderedlist").在jQuery中,我们这样做:
$(document).ready(function() {
$("#orderedlist").addClass("red");
});
这里将starterkit中的一个CSS样式red附加到了orderedlist上(译者Keel注:参考测试包中的css目录下的core.css,其中定义了red样式)。因此,在你刷新了starterkit.html后,你将会看到第一个有序列表(ordered list )背景色变成了红色,而第二个有序列表没有变化.
现在,让我们添加一些新的样式到list的子节点.
$(document).ready(function() {
$("#orderedlist > li").addClass("blue");
});
这样,所有orderedlist中的li都附加了样式"blue"。
现在我们再做个复杂一点的,当把鼠标放在li对象上面和移开时进行样式切换,但只在list的最后一个element上生效。
$(document).ready(function() {
$("#orderedlist li:last").hover(function() {
$(this).addClass("green");
}, function() {
$(this).removeClass("green");
});
});
还有大量的类似的CSS和XPath例子,更多的例子和列表可以在这里找到。(译者Keel注:入门看此文,修行在个人,要想在入门之后懂更多,所以这段话的几个链接迟早是要必看的!不会又要翻译吧...^_^!)
每一个onXXX事件都有效,如onclick,onchange,onsubmit等,都有jQuery等价表示方法(译者Keel注:jQuery不喜欢onXXX,所以都改成了XXX,去掉了on)。其他的一些事件,如ready和hover,也提供了相应的方法。
你可以在Visual jQuery找到全部的事件列表,在Events栏目下.
用这些选择器和事件你已经可以做很多的事情了,但这里有一个更强的好东东!
$(document).ready(function() {
$("#orderedlist").find("li").each(function(i) {
$(this).html( $(this).html() + " BAM! " + i );
});
});
find() 让你在已经选择的element中作条件查找,因此 $("#orderedlist).find("li") 就像 $("#orderedlist li")一样。each()方法迭代了所有的li,并可以在此基础上作更多的处理。 大部分的方法,如addClass(), 都可以用它们自己的 each() 。在这个例子中, html()用来获取每个li的html文本, 追加一些文字,并将之设置为li的html文本。(译者Keel注:从这个例子可以看到.html()方法是获取对象的html代码,而.html('xxx')是设置'xxx'为对象的html代码)
另一个经常碰到的任务是在没有被jQuery覆盖的DOM元素上call一些方法,想像一个在你用AJAX方式成功提交后的reset:
$(document).ready(function() {
// use this to reset a single form
$("#reset").click(function() {
$("#form")[0].reset();
});
});
(译者Keel注:这里作者将form的id也写成了form,源文件有<form id="form">,这是非常不好的写法,你可以将这个ID改成form1或者testForm,然后用$("#form1")或者$("#testForm")来表示它,再进行测试。)
这个代码选择了所有ID为"form"的元素,并在其第一个上call了一个reset()。如果你有一个以上的form,你可以这样做:
$(document).ready(function() {
// use this to reset several forms at once
$("#reset").click(function() {
$("form").each(function() {
this.reset();
});
});
});
(译者Keel注:请注意一定要亲自将这些代码写在custom.js中并在starterkit.html上测试效果才能有所体会!必要时要观察starterkit.html的html代码)
这样你在点击Reset链接后,就选择了文档中所有的form元素,并对它们都执行了一次reset()。
还有一个你可能要面对的问题是不希望某些特定的元素被选择。jQuery 提供了filter() 和not() 方法来解决这个问题。 filter()以过滤表达式来减少不符合的被选择项, not()则用来取消所有符合过滤表达式的被选择项. 考虑一个无序的list,你想要选择所有的没有ul子元素的li元素。
$(document).ready(function() {
$("li").not("[ul]").css("border", "1px solid black");
});
这个代码选择了所有的li元素,然后去除了没有ul子元素的li元素。刷新浏览器后,所有的li元素都有了一个边框,只有ul子元素的那个li元素例外。
(译者Keel注:请注意体会方便之极的css()方法,并再次提醒请务必实际测试观察效果,比方说换个CSS样式呢?再加一个CSS样式呢?像这样:$("li").not("[ul]").css("border", "1px solid black").css("color","red");)
上面代码中的[expression] 语法是从XPath而来,可以在子元素和属性(elements and attributes)上用作过滤器,比如你可能想选择所有的带有name属性的链接:
$(document).ready(function() {
$("a[name]").background("#eee"); //原文为“$("a[@name]").background("#eee");”在jQuery1.2及以上版本中,@符号应该去除
});
这个代码给所有带有name属性的链接加了一个背景色。(译者Keel注:这个颜色太不明显了,建议写成$("a[name]").background("red");) [注:在jQuery1.2及以上版本中,@符号应该去除,下文中不再说明]
更常见的情况是以name来选择链接,你可能需要选择一个有特点href属性的链接,这在不同的浏览器下对href的理解可能会不一致,所以我们的部分匹配("*=")的方式来代替完全匹配("="):
$(document).ready(function() {
$("a[href*=/content/gallery]").click(function() {
// do something with all links that point somewhere to /content/gallery
});
});
到现在为止,选择器都用来选择子元素或者是过滤元素。另外还有一种情况是选择上一个或者下一个元素,比如一个FAQ的页面,答案首先会隐藏,当问题点击时,答案显示出来,jQuery代码如下:
$(document).ready(function() {
$('#faq').find('dd').hide().end().find('dt').click(function() {
var answer = $(this).next();
if (answer.is(':visible')) {
answer.slideUp();
} else {
answer.slideDown();
}
});
});
这里我们用了一些链式表达法来减少代码量,而且看上去更直观更容易理解。像'#faq' 只选择了一次,利用end()方法,第一次find()方法会结束(undone),所以我们可以接着在后面继续find('dt'),而不需要再写$('#faq').find('dt')。
在点击事件中的,我们用 $(this).next() 来找到dt下面紧接的一个dd元素,这让我们可以快速地选择在被点击问题下面的答案。
(译者Keel注:这个例子真是太酷了,FAQ中的答案可以收缩!从利用next()的思路到实现这些效果都有很多地方需要我们消化,注意 if (answer.is(':visible'))用法,注意answer.slideUp();不懂的地方赶紧查我在最开始提到的两个必看API文档)
除了选择同级别的元素外,你也可以选择父级的元素。可能你想在用户鼠标移到文章某段的某个链接时,它的父级元素--也就是文章的这一段突出显示,试试这个:
$(document).ready(function() {
$("a").hover(function() {
$(this).parents("p").addClass("highlight");
}, function() {
$(this).parents("p").removeClass("highlight");
});
});
测试效果可以看到,移到文章某段的链接时,它所在的段全用上highlight样式,移走之后又恢复原样。
(译者Keel注:highlight是core.css中定义的样式,你也可以改变它,注意这里有第二个function()这是hover方法的特点,请在API文档中查阅hover,上面也有例子说明)在我们继续之前我们先来看看这一步: jQuery会让代码变得更短从而更容易理解和维护,下面是$(document).ready(callback)的缩写法:
$(function() {
// code to execute when the DOM is ready
});
应用到我们的Hello world例子中,可以这样:
$(function() {
$("a").click(function() {
alert("Hello world!");
});
});
现在,我们手上有了这些基础的知识,我们可以更进一步的探索其它方面的东西,就从AJAX开始!
本章的相关链接:
Rate me:使用AJAX
在这一部分我们写了一个小小的AJAX应用,它能够rate一些东西(译Keel注:就是对某些东西投票),就像在youtube.com上面看到的一样。
首先我们需要一些服务器端代码,这个例子中用到了一个PHP文件,读取rating参数然后返回rating总数和平均数。看一下rate.php代码.
虽然这些例子也可以不使用AJAX来实现,但显示我们不会那么做,我们用jQuery生成一个DIV容器,ID是"rating".
$(document).ready(function() {
// generate markup
var ratingMarkup = ["Please rate: "];
for(var i=1; i <= 5; i++) {
ratingMarkup[ratingMarkup.length] = "<a href='#'>" + i + "</a> ";
}
// add markup to container and applier click handlers to anchors
$("#rating").append( ratingMarkup.join('') ).find("a").click(function(e) {
e.preventDefault();
// send requests
$.post("rate.php", {rating: $(this).html()}, function(xml) {
// format result
var result = [
"Thanks for rating, current average: ",
$("average", xml).text(),
", number of votes: ",
$("count", xml).text()
];
// output result
$("#rating").html(result.join(''));
} );
});
});
这段代码生成了5个链接,并将它们追加到id为"rating"容器中,当其中一个链接被点击时,该链接标明的分数就会以rating参数形式发送到rate.php,然后,结果将以XML形式会从服务器端传回来,添加到容器中,替代这些链接。
如果你没有一个安装过PHP的webserver,你可以看看这个在线的例子.
不使用javascript实现的例子可以访问 softonic.de 点击 "Kurz bewerten!"
更多的AJAX方法可以从这里 找到,或者看看API文档 下面的AJAX filed under AJAX.
(译者Keel注:这个在线实例从国内访问还是比较慢的,点击后要等一会儿才能看到结果,可以考虑对它进行修改,比如加上loading,投票后加上再投票的返回链接等。此外,这个例子中还是有很多需要进一步消化的地方,看不懂的地方请参考API文档。)
一个在使用AJAX载入内容时经常发生的问题是:当载入一个事件句柄到一个HTML文档时,还需要在载入内容上应用这些事件,你不得不在内容加载完成后应用这些事件句柄,为了防止代码重复执行,你可能用到如下一个function:
// lets use the shortcut
$(function() {
var addClickHandlers = function() {
$("a.clickMeToLoadContent").click(function() {
$("#target").load(this.href, addClickHandlers);
});
};
addClickHandlers();
});
现在,addClickHandlers只在DOM载入完成后执行一次,这是在用户每次点击具有clickMeToLoadContent 这个样式的链接并且内容加载完成后.
请注意addClickHandlers函数是作为一个局部变量定义的,而不是全局变量(如:function addClickHandlers() {...}),这样做是为了防止与其他的全局变量或者函数相冲突.
另一个常见的问题是关于回调(callback)的参数。你可以通过一个额外的参数指定回调的方法,简单的办法是将这个回调方法包含在一个其它的function中:
// get some data
var foobar = ...;
// specify handler, it needs data as a paramter
var handler = function(data) {
...
};
// add click handler and pass foobar!
$('a').click( function(event) { handler(foobar); } );
// if you need the context of the original handler, use apply:
$('a').click( function(event) { handler.apply(this, [foobar]); } );
用到简单的AJAX后,我们可以认为已经非常之“web2.0”了,但是到现在为止,我们还缺少一些酷炫的效果。下一节将会谈到这些效果.
本章的相关链接:
Animate me(让我生动起来):使用FX
一些动态的效果可以使用 show() 和 hide()来表现:
$(document).ready(function() {
$("a").toggle(function() {
$(".stuff").hide('slow');
}, function() {
$(".stuff").show('fast');
});
});
你可以与 animate()联合起来创建一些效果,如一个带渐显的滑动效果:
$(document).ready(function() {
$("a").toggle(function() {
$(".stuff").animate({
height: 'hide',
opacity: 'hide'
}, 'slow');
}, function() {
$(".stuff").animate({
height: 'show',
opacity: 'show'
}, 'slow');
});
});
很多不错的效果可以访问interface plugin collection. 这个站点提供了很多demos和文档
这些效果插件是位于jQuery插件列表的前面的,当然也有很多其他的插件,比如我们下一章讲到的表格排序插件。
本章的相关链接:
Sort me(将我有序化):使用tablesorter插件(表格排序)
这个表格排序插件能让我们在客户端按某一列进行排序,引入jQuery和这个插件的js文件,然后告诉插件你想要哪个表格拥有排序功能。
要测试这个例子,先在starterkit.html中加上像下面这一行的代码:
<script src="lib/jquery.tablesorter.js" type="text/javascript"></script>
然后可以这样调用不着:
$(document).ready(function() {
$("#large").tableSorter();
});
现在点击表格的第一行head区域,你可以看到排序的效果,再次点击会按倒过来的顺序进行排列。
这个表格还可以加一些突出显示的效果,我们可以做这样一个隔行背景色(斑马线)效果:
$(document).ready(function() {
$("#large").tableSorter({
stripingRowClass: ['odd','even'], // Class names for striping supplyed as a array.
stripRowsOnStartUp: true // Strip rows on tableSorter init.
});
});
关于这个插件的更多例子和文档可以在 tablesorter首页找到.
几乎所有的特件都是这样用的:先include插件的js文件,然后在某些元素上使用插件定义的方法,当然也有一些参数选项是可以配置的
经常更新的插件列表可以从jQuery官方站 on the jQuery site找到.
当你更经常地使用jQuery时,你会发现将你自己的代码打包成插件是很有用处的,它能方便地让你的公司或者其他人进行重用.下一章我们将谈到如何构建一个自己的插件.
本章的相关链接:
Plug me:制作自己的插件
写一个自己的jQuery插件是非常容易的,如果你按照下面的原则来做,可以让其他人也容易地结合使用你的插件.
- 为你的插件取一个名字,在这个例子里面我们叫它"foobar".
- 创建一个像这样的文件:jquery.[yourpluginname].js,比如我们创建一个jquery.foobar.js
- 创建一个或更多的插件方法,使用继承jQuery对象的方式,如:
jQuery.fn.foobar = function() { // do something }; - 可选的:创建一个用于帮助说明的函数,如:
jQuery.fooBar = { height: 5, calculateBar = function() { ... }, checkDependencies = function() { ... } };你现在可以在你的插件中使用这些帮助函数了:
jQuery.fn.foobar = function() { // do something jQuery.foobar.checkDependencies(value); // do something else }; - 可选的l:创建一个默认的初始参数配置,这些配置也可以由用户自行设定,如:
jQuery.fn.foobar = function(options) { var settings = { value: 5, name: "pete", bar: 655 }; if(options) { jQuery.extend(settings, options); } };现在可以无需做任何配置地使用插件了,默认的参数在此时生效:
$("...").foobar();或者加入这些参数定义:
$("...").foobar({ value: 123, bar: 9 });
如果你release你的插件, 你还应该提供一些例子和文档,大部分的插件都具备这些良好的参考文档.
现在你应该有了写一个插件的基础,让我们试着用这些知识写一个自己的插件.
很多人试着控制所有的radio或者checkbox是否被选中,比如:
$("input[type='checkbox']").each(function() {
this.checked = true;
// or, to uncheck
this.checked = false;
// or, to toggle
this.checked = !this.checked;
});
$('input:checkbox').each(function() {
无论何时候,当你的代码出现each时,你应该重写上面的代码来构造一个插件,很直接地:
$.fn.check = function() {
return this.each(function() {
this.checked = true;
});
};
这个插件现在可以这样用:
$('input:checkbox').check();
现在你应该还可以写出uncheck()和toggleCheck()了.但是先停一下,让我们的插件接收一些参数.
$.fn.check = function(mode) {
var mode = mode || 'on'; // if mode is undefined, use 'on' as default
return this.each(function() {
switch(mode) {
case 'on':
this.checked = true;
break;
case 'off':
this.checked = false;
break;
case 'toggle':
this.checked = !this.checked;
break;
}
});
};
这里我们设置了默认的参数,所以将"on"参数省略也是可以的,当然也可以加上"on","off", 或 "toggle",如:
$("input[type='checkbox']").check();
$("input[type='checkbox']").check('on');
$("input[type='checkbox']").check('off');
$("input[type='checkbox']").check('toggle');
如果有多于一个的参数设置会稍稍有点复杂,在使用时如果只想设置第二个参数,则要在第一个参数位置写入null.
从上一章的tablesorter插件用法我们可以看到,既可以省略所有参数来使用或者通过一个 key/value 对来重新设置每个参数.
作为一个练习,你可以试着将 第四章 的功能重写为一个插件.这个插件的骨架应该是像这样的:
$.fn.rateMe = function(options) {
var container = this; // instead of selecting a static container with $("#rating"), we now use the jQuery context
var settings = {
url: "rate.php"
// put more defaults here
// remember to put a comma (",") after each pair, but not after the last one!
};
if(options) { // check if options are present before extending the settings
$.extend(settings, options);
}
// ...
// rest of the code
// ...
return this; // if possible, return "this" to not break the chain
});
Next steps(下一步)
如果你想做更好的javascript开发,建议你使用一个叫 FireBug的firefox插件. 它提供了断点调试(比alert强多了)、观察DOM变化等很多漂亮的功能
如果你还有未解决的问题,或者新的想法与建议,你可以使用jQuery的邮件列表 jQuery mailing list.
还有什么...
大大感谢John Resig创造了这么好的library! 感谢jQuery community 为John提供了如此多的咖啡和其他的一切!
© 2006, Jörn Zaefferer - last update: 2006-09-12
中文版翻译:Keel 上次更新:2006-12-13 -- 最后更新: 2009-3-10
一个成功的博客必须知道的80个博客工具
Feedblitz:邮件订阅工具。
MyBloglog:博客统计工具,可以显示最近访客。
Performancing:博客编辑器,firefox插件。
Dijjer | Redswoosh | Pando :减少你的流量,尤其对于富媒体文件比较多的博客,免费,易用。
Dead-Links:坏链检查工具。
Pingomatic:自动ping主流博客搜索引擎的工具,wordpress自带。
RSS Re-mixers:rss聚合工具,可以把多个rssfeed聚合到一个feed里面。
Feedostyle:rss聚合工具,把其他任意一个rss聚合到你的博客上面。
Webshotspro:即时生成博客的预览图。
SiteTimer:检查你的博客首页完全显示要多长时间。如果你想你的博客能够留住读者的话,从开始到完全显示的时间,最好在4秒以内。博客联盟测试的时候用了13秒,崩溃:)可能跟国外网站的缘故。
Web based image resizing and editing tools:在线图像编辑工具。
Flock:可以和firefox媲美的浏览器。支持直接从flock发布日志到blog的功能。
Copyblogger:像写广告文案一样写作博客的技巧。
博客小玩意:
Springwidgets:很多小玩意,如时钟,计数器,小游戏等等。
Majikwidget:付费定制属于自己的小玩意。
Alexa | Alexaholic:显示你的博客在alexa上面的排名情况。
PollDaddy:投票系统,可以非常方便的在你的博客上插入漂亮的投票模板。
Chipin:可以用来向大家征集donation,呵呵。
ChatCreator:留言本生成,可以自定义外观。
Tagcloud:为你的博客生成标签云,类似于Ultimate Tag Warrior所起的作用。
Videoegg:在日志里添加视频的工具。
MapKit:以最简单的方法向你的博客里面添加地图。
Plugoo:留言框生成工具,支持blogger用msn等及时通讯软件跟读者交流。
Snap:链接预览工具。
Eurekster:社会化搜索引擎。
流量统计工具:
一般的流量统计工具:Statcounter | Getclicky | Google Analytics
高级流量统计工具:
CrazyEgg |
Measuremap
博客进阶和博客搜索引擎优化工具:
101 web marketing ideas and tips:来自最好的seo博客之一的 Seopedia.com:90条博客进阶技巧。
Seomoz: SEO Page Strength:博客评估工具,如博客连接数,del.icio.us连接数,technorati的连接数等等。
Blog Search Engines:含一系列的博客搜索引擎,网站搜索引擎,rss聚合站点等。
Adgridwork:文本链接广告系统。
Google Webmasters Central:google网站管理工具。
Yahoo:SiteExplorer:yahoo提供的检查博客外链的工具。
Blogburst:通过把你的博客加入到blog network里面,以提高你的博客流量,知名度等。
Dmoz:全球最大,最权威的网站分类目录。如果能够把你的博客提交到这个站点的话,对于提高博客pr值,提高博客在搜索引擎里面的权重,都有非常重要的影响。
Competitio.us:分析你和跟你有竞争关系的博客的对比情况。
Technorati - 全球最大的rss搜索引擎。
Blog Directory -博客分类目录,对提高博客排名有很大的帮助。
WordPress and SEO:针对wordpress进行搜索引擎优化的经典教程。
代码验证工具
W3C validator:验证 HTML 和 XHTML。
Feedvalidator :feed验证工具。
CSS validator:css验证工具。
如何使用博客赚钱?
Other advertising networks besides google adsense:除google adsense 以外的赚钱方法大全。
Problogger:教blogger如何利用博客赚钱的博客。
ReviewMe | PayPerPost | SponsoredReviews:通过参与测评服务,产品来获得收入。
Text Link Ads:通过出售链接位赚钱。
Blogads | FederatedMedia(A+):广告中介商,通过出卖广告位给你赚钱。对博客的要求比较高。
Bloggerkit:展示在amazon上面跟你的内容相关的产品,按出售价格提成。
Advolcano:CPT广告(每广告位时间成本,譬如包天、包时等)
booBox.com:出售跟博客内容相关的产品。
Quantcast:开放的投票系统,通过博客读者对广告商服务的投票来获利。
有用的文章
我最喜爱的50个blogging资源 [by Neil Patel]
博客写作必须知道的知识:in Ten Minutes, by Stephen King
原文链接:http://www.makeuseof.com/tag/80-tools-for-bloggers/
翻译地址:http://blogunion.org/blogging-tools/80-tools-for-bloggers.html
PR在线(批量)查询
PR查询地址:http://www.blogpagerank.cn/
PR批量查询:http://www.blogpagerank.cn/blogspr.php
SEO经验谈
在网络日益发达和生活条件日益提高的今天,电脑的使用极大地普及,用户通过互联网获取自己需求肯定会成为一个大趋势。搜索引擎的作用越发重要了。
反过来看,作为网站经营者,如何在众多的网站中将自己的站点排在搜索引擎的靠前位置(特别是首页)也成为一个特别重要方面。诸如百度竞价的渠道可以在一定程度上解决这个问题,然而该方式除了需要支付高价外,这也不是治本的方式。
SEO无疑成为一个经济的、可靠的、受欢迎的渠道。
下面阐述本人对SEO的理解以及在这方面的一点经验:
URL规划:
另外,可以进行在URL中添加关键词的处理,每个关键词中间用“-”或者逗号“,”分开,并且关键词最多不要超过5个。
域名相关:
一个“友好”的域名应该是这样的: (1)域名具有语义化,比如做SEO方面的,“seo.com”比“soe.com”就好了一万倍! (2)域名长度:域名的长度不要超过10个字符,这里包括域名的后缀,最好的应该是6个字符以内。但是现在这样好的域名不好注册了,那么可以从用户体验方面出发,比如什么样的域名用户容易记住?最明显的例子就是,1.“hao123.com” 2.六间房弃用“6rooms.com”而高价购买“6.cn”…
网站结构:
在web2.0+的今天,不是说大家推崇DIV+CSS就不能再使用table进行网站布局了,这个观念首先需要矫正的。其实在很多时候,比如数据的显示方面,用Table进行布局还是很好的方式。
导航:
另外一些网站采用JavaScript或者flash展示网站的导航,这种方法也是不值得推崇的。因为搜索引擎对JavaScript和flash(脚本)的解析是比较低的。所以最好不要这么做!
另外比较重要的方面是导航的位置,必须出现在页面的第一屏,而不是其他不起眼的位置!
Sitemap的运用:
页面的深度:
而且二级域名的使用需要注意其语义化,比如做论坛就可以采用“bbs.example.com”的形式,而不要采用不相关的“sbb.example.com”这样的形式。
服务器相关:
关于这方面的经验就是:不要频繁地改变网站的结构和布局,不要轻易地更换网站的域名,不要频繁地对网站进行(页面)重建操作,更重要的是,选择和使用安全性和稳定性高的服务器!
举个简单的例子,当搜索蜘蛛前来访问的时候正好赶上你的站点在维护,甚至是网站因故宕机——那么这次的搜索蜘蛛的访问是无效的。如果频繁出现这样的问题,其直接结果是:搜索蜘蛛不再“喜欢”该站点而“鲜来问津”,网站被收录的页面也会因此下降很多!
对HTML标记的合理运用:
关键词的合理部署:
现在一些网站的关键词也往往是这样的顺序:“网站标题--页面标题—tags列表--…”,这并不是一种良好的方式。在我看来,除了首页和比较重要的(比如分类页的首页)页面可以采取这种结构外,其他的内容页面应该是“页面标题—tags列表--网站标题…”这样的顺序,每个内容也的关键词首页应该是不一样的。
关键词的确认应该以页面内容而定,不要试图布置一些页面没出现过的词语,很没有意义。这样的方式除了在概率上可能会起到类“标题党”的作用,从长远角度出发,这样的方式只会给网站“自掘坟墓”。
善用语义化的标记:
另外,如果页面出现比较多的图片(尤其是图片站)的话,就十分有必要给每张图片添加title和alt属性,否则图片除了美观和增加服务器负荷的作用外对搜索引擎没有任何意义。
善用内链:
不断地原创和持续的更新:
另外,如果站点能够持续地更新内容,并且这种更新的时间是很有规律的,那么——搜索蜘蛛会十分喜欢这样的行为,无论是在页面收录的数量上,还是对页面的排名上都会有一个不错的结果。
给转载内容的建议:
这里我的经验就是,去掉被转载内容中无用的那些标记,比如原来页面出现的DIV标记、多余的空格符 ;、以及那些没必要的类似于“<font size=”XX” …>”之类的东西。其实这还远远不够的,需要去掉那些无用的与需求不相关的内容、需要重新安排内用结构(顺序)、需要重新规划关键词并且进行SEO方面处理,比如添加下划线、增粗处理等。
用户体验:
其实SEO在我看来可以归结为“用户体验”的一个方面。只不过这种“用户”的涵盖范围要大了许多。
SEO的本质问题:
这里可以举例说明这个问题:当你优化一个(没有实际价值的)词的时候,在各大搜索引擎使用该词搜索的时候你的页面被排在第一位,然而却没有任何意义!想想看,除了自己去搜索和查看到这样的“成就”窃喜外,对其他人没有任何价值!同样的,如果关键词的布置不合理,用户也只能通过人性化的方式搜索想要的结果——那么你的优化也是不能达到预期效果的。举个简单的例子,你把“语录,毛泽东”优化到了第一位,然而用户只会按照“毛泽东语录”的方式进行查询,其结果是显而易见的了。
当SEO优化者看清楚这个问题的本质的时候,SEO自然就变得不再那么盲目和艰难了。
文章转载自很实用网站:www.henshiyong.com
web标准设计师常见问题
怎样才是符合web标准?
简单说就是不用HTML+table来设计页面,改用XHTML+CSS来实现,布局最好是用DIV+css。
web标准在哪里校验?
web标准代码校验就是检查你制作好的页面是否完全符合web标准。通常可以到W3C的网站去校验。
什么是DocType,有什么用?
DOCTYPE是document type(文档类型)的简写,用来说明你的网页是什么标识语言(XHTML或者HTML)是什么版本。
我应该使用是么样的DOCTYPE?
初次学习web标准的设计师推荐使用XHTML 1.0过渡式的DTD,代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
遵循web标准就不能使用table表格了吗?
可以使用table表格。只是表格仅仅用于其本意:展示数据列表。而不允许使用表格排版和定位。
遵循web标准可以使用Flash吗?
可以。但是<embed>不允许使用。暂时只能采用js调用来通过W3C校验。
不用表格可以制作出漂亮的页面布局吗?
可以。CSS可以实现几乎所有用table实现的布局。参考成功网站:www.macromedia.com,www.mp3.com,www.blogger.com,www.espn.com
有什么关于web标准好书推荐吗?
web标准的概念和实践推荐Zeldman的《网站重构--用web标准进行设计》;CSS入门和进阶推荐Eric Meyer的《CSS权威指南》《More Eric Meyer on CSS》。 本站为此问题专门收集了一些css书籍教程。
CSS布局比表格难吗?
这要看你怎么想了。变革和观念转换总是有困难的,你认为这个转变是值得的,那么你会发现CSS并不比表格难。我个人觉得用css更简单,功能更强大,只要用心学习,入门是非常快的。
表格布局是不是马上要淘汰了?
不会。至少现在还有成千上万的(老的和新建的)网页依然使用表格布局。新技术的过渡和普及需要一定时间。
网页设计必修课 div+css书籍教程大全
随着Web 2.0的时代浪潮的到来,web网页标准化DIV+CSS的设计方式正逐渐取代传统的table表格布局模式,对CSS的学习也成为网页设计人员的必修课。为此,本站专门找到了一些div+css设计的书籍教程打包下载地址, 供各位div+css学者学习。
导航经典推荐的23种div+css代码实战DIV+CSS动易模板培训课(教程与录像)
div+css布局大全
40款网页模板源文件(DIV+CSS)
Div+CSS布局实例教程(chm)_建站学
DIV+CSS模板---新整理第4期50套
综合HTML和CSS_更聪明更快的学习方法_html教程
div,css教程(共27个分卷).part07
《精通CSS滤镜》
CSS Tab Designer V2.0.0 快速地生成CSS导航栏或列表
css编辑软件 围天层叠样式表(CSS)编辑器 V3.6
《美工神话--CSS网站布局与美化》10
CSS与DHTML精髓
精通CSS.DIV网页样式与布局》配套视频教程
综合HTML和CSS_更聪明更快的学习方法_html教程
CSS僵尸地图
使用HTML XHTML和CSS创建酷站_html教程
WordPress皮肤_ CSS Gallery
网页制作全接触—HTML4.0+CSS
css鼠标滑过内容切换代码
CS1.6模仿CSS样式-仿动态金属武器模型(new)
HTML和CSS经典布局
CSS特效代码生成器 v1
CSS 设计艺术 PDF版
CSS风格df_simpress_v1
含有索引的CSS 2.0中文手册 v1.0
缩略图边框装饰CSS代码
19个精彩的CSS菜单打包下载
css2速查手册
CSS中文完全参考手册3.0
最全的css2.0+html标签帮助文档和教程
CSS代码生成器
div+css布局中常用元素:ol ul li dt dl dd用法解释
DIV +CSS网页布局中常用的列表元素ul ol li dl dt dd用法解释,块级元素div尽量少用,和table一样,嵌套越少越好
ol 有序列表。
<ol>
<li>……</li>
<li>……</li>
<li>……</li>
</ol>
表现为:
1……
2……
3……
ul 无序列表,表现为li前面是大圆点而不是123
<ul>
<li>……</li>
<li>……</li>
</ul>
很多人容易忽略 dl dt dd的用法
dl 内容块
dt 内容块的标题
dd 内容
可以这么写:
<dl>
<dt>标题title</dt>
<dd>内容content1</dd>
<dd>内容content2</dd>
</dl>
dt 和dd中可以再加入 ol ul li和p
理解这些以后,在使用div布局的时候,会方便很多,w3c提供了很多元素辅助布局。
W3C发布的标准
HTML4.0
HyperText Markup Language(HTML,超文本标识语言)广泛用于现在的网页,HTML目的是为文档增加结构信息,例如表示标题,
表示段落;浏览器可以解析这些文档的结构,并用相应的表现形式表现出来。例如:浏览器会将...之间的内容用粗体显示。
设计师也可以通过CSS(Cascading Style Sheets)来定义某种结构以什么形式表现出来。
XML1.0
XML是Extensible Markup Language(可扩展标识语言)的简写。XML类似HTML也是标识语言,不同的地方是:HTML有固定的标签,而XML允许你自己定义自己的标签, 甚至允许你通过XML namespaces为一个文档定义多套设定。看一个XML例子:
<addressbook>
<entry>
<name>AJIE</name><email>ajie33@hotmail.com</email>
</entry>
<entry><name>ALLAN</name><email>neo_n@21cn.com</email>
</entry>
<entry><name>YAHOO</name><email>tingpeng@msn.com</email>
</entry>
</addressbook>
一些XML的应用,例如XHTML和MathML,已经成为W3C推荐规范。你同样可以通过样式规范(CSS和XSL),来定义XML标签的表现形 式。XML文档目前还不能直接用浏览器显示,页面展现依然采用HTML或者XHTML,XML现在大多用于服务器与服务器(系统与系统)之间的数据交换。
CSS2.0
CSS是Cascading Style Sheets层叠样式表的缩写。通过CSS可以控制HTML或者XML标签的表现形式。W3C推荐使用CSS布局方法,使得web更加简单,结构更加清晰。
XHTML1.0
XHTML实际上就是将HTML根据XML规范重新定义一遍。它的标签与HTML4.0一致,而格式严格遵循XML规范。因此,虽然XHTML与HTML在浏览器中一样显示,但如果你要转换成PDF,那么XHTML会容易的多。
XHTML有三种DTD定义:严格的(strict),过渡的(Transitional),框架的(Frameset)。 DTD是Document Type Definition文档类型定义的缩写。它写在XHTML文件的最开始,告诉浏览器这个文档符合什么规范,用什么规范来解析。
DOM1.0
DOM是Document Object Model文档对象模型的缩写。DOM给了脚本语言(类似ECMAScript)无限发挥的能力。它使脚本语言很容易访问到整个文档的结构、内容和表现。
W3C与DIV+CSS对SEO到底有多大的帮助
W3C网页设计标准是一种技术也是一种思想。
现在基本上很多高端的客户都会要求按照W3C标准来设计网站。在今年和去年这两年时间里,国内很多的门户网站都已经按照W3C标准对网站整体进行代码重构。

用W3C标准来设计网站,有个好处:提高用户体验,加快网页下载速度。按照W3C标准设计的网站,用户浏览速度比较快,因为网站的代码比较简洁。
有一部分的朋友说,做好DIV+CSS,网站优化就等于做好了80%的工作。但是我们并不赞同这个观点。
传统的表格与DIV+CSS对于网站排名的影响,后者并没有什么优势可言。因为实际上用Div+CSS来设计的网站,也并没有因此得到搜索引擎的特别的照顾。绝不能简单地把DIV+CSS理解成SEO。

但是使用DIV+CSS来设计网站,确实能够对SEO起到一定的帮助。
例如:
一、减少使用表格
表格层层嵌套,确实对SEO与用户体验有不利的影响,这同时也影响网页的下载速度。
二、降低网页体积
上百K的网页,不利于SEO,不利于搜索引擎的蜘蛛爬行。DIV+CSS设计网页,能够让精简网页HTML代码,让网页体积变得更小。
三、重要信息优先让搜索引擎蜘蛛爬取
通过DIV+CSS对网页的布局,可以让一些重要的链接、文字信息,优先让搜索引擎蜘蛛爬取。这对于SEO也有帮助。
给广大网编的建议:对于是用DIV+CSS设计网站还是用表格来设计网站,可以根据自己的技术实力来决定。DIV+CSS设计的网站,这个和域名一样,并没有多少先天性的优势,搜索引擎和用户一样,最终看重的是一个网站的内容。
提升网站价值,重点是在于后天的培养。
DIV+CSS神话
作为一名2009年的 Web 设计师,你是否好意思承认自己的代码中使用了Table,如果是,你是一个有勇气的人,Web 设计是个奇怪的行业,你可以将自己的网站设计得像晚报的分类广告,或者楼道里的开锁广告,但千万别让人知道你使用了 Table,在你的源代码中发现 Table 就像一个销售被人掀起裤脚发现穿了白袜子一样。
Table 是如此丑陋,臃肿,哪怕只显示一段简单的内容,你也需要 <table><tr><td> 这三个基本的标签,每个标签里面还要加上一堆乱七八糟的属性,不像<div>,既简单,又整洁,又时尚,它和 CSS 珠联璧合,琴瑟和谐,它们构成最完美的 Box 模型,他们象现实中的箱子,你把东西放进去,然后,很自由地对他们进行排列,厌烦了一种布局,没关系,简单地改动一下 CSS 定义,一种全新的布局便诞生了;不象 Table,Table 像食堂里的餐具柜,一排排,一列列,土里土气,油腻腻的,象我们的父辈,邋遢,什么都往家里拿,胡乱堆在角落里,如果 Div 是小资,Table 就是老三届,他们不属于这个时代。
也就是近几年的事,至多不过三五年,W3C是一个人人都认为重要但人人都不喜欢的组织,他们的官方网站十分丑陋,我敢说平生没见过这么丑陋的网站,但他们的网站是为数不多的可以通过全部W3C标准验证的网站,这意味着,他们的网站在语法上,在结构上,在可访问性上是完美的,虽然依旧十分丑陋。不过这是笑谈,W3C非常重要,否则微软会把全体 Web 开发工程师带到万劫不复的境地,还好,Netscape 死后,涅磐出 Firefox,而 Opera 在 Firefox 横空出世之后虽然没得到任何好处,至少得到了精神上的支持,看到没,终于有大哥出来收拾你。乔布斯复出后,苹果重返昔日的光芒,这时人们才知道世界上还有一个叫做 Safari 的浏览器,所有这一切加在一起,让 W3C 真正有了存在的必要。
W3C 说,Table 可以用来容纳文字,格式文字,图片,链接,表单,以及其它 Table ... 但是,Table 不应该单纯用来做网页布局(Tables should not be used purely as a means to layout document content),理由是,当 Web 被非可视化设备渲染的时候,Table 会出现问题,他们指定是屏幕阅读器以及盲文浏览器,另外,Table 在大型显示设备上会强迫用户左右滚动,因此,Web 设计者应该使用 CSS 而不是 Table。参见 W3C HTML 4.01 关于 Table 的定义。 W3C 说这段话的时候,是1999年12月24日,那时尽管 CSS 早已诞生,但并没有多少人使用,最初的 Web 像一个在线版的文档,并没有成为现在这样的平台,不需要过多过多地考虑布局问题,随着互联网第一次泡沫的形成,涌现出大量的门户网站,门户网站是 Table 布局的始作俑者,因为他们的首页比一整份报纸的所有版面拼接在一起还复杂,Table 在这方面十分顺手,结合 colspan 和 rolspan,你几乎能够实现任何复杂的版面。
这种布局风格在2000年代初,一直到中期仍然十分流行,尤其国内,在大为美的潜意识下,人们把所有能塞到一个页面的东西都塞进了首页,Table 就像一个旧时代的管家,把所有东西虽不能井井有序,但至少是一样不少地编排起来。然而这样的 Web 终于到了让人厌恶的地步,随着搜索,RSS 订阅,以及以博客为代表的个性化 Web 的出现,人们有更多渠道获得信息,而不必去访问那几个让人几乎要晕过去的门户的首页,于是出现了一种清新的,轻量的 Web 风,使用更简单的布局,更明快的配色,大图标,大 Banner,以及更容易阅读的大字体,同时,在这个时候,CSS 已经非常成熟,而 Firefox, Opera, Safari 为代表的浏览器,在遵守 W3C 标准方面要远远好过 IE,人们终于认识到 CSS 的威力。因为 CSS 在布局上,其核心是一个 Box 模型,人们必须为 CSS 找一个可以依附的容器对象。
Div 成为幸运者一方面因为它天生就是 Box 的最佳原型,在语义上,Div 代表页面的一个区域,在外形上,它四四方方,更重要的是,它不像 <P> 或 <a> 那样事先已经被赋予特殊的语义(虽然它们也能用于 Box 模型);另一方面,则出于人们对 Table 统治一个臃肿时代的憎恶,一个时代的结束,继任者都会努力抹去旧时代的痕迹,那些旧时代的象征或代表的命运多半如此,人们并不是简单地忘却它们,而是断然划清界限。
Table 的一切不公平待遇就此开始。为什么说不公平,W3C 不建议 Table 布局的时候,只说应使用 CSS 代替,这是什么意思,Table 不支持 CSS 吗?当然支持,而且,由于 Table 作为老牌的 HTML 对象,它的地位曾如此重要,任何浏览器都对 Table 提供了最完美的支持,包括 CSS 支持。当人们拥抱 Div 的时候,似乎忘记了 Table 也是 Box,而且是一个拥有多个内格的 Box,Table 作为一个整体,和 Div 在 Box 模型方面没有任何区别,而它的内格,除了 Margin 之外,仍然是一个 Box,内格不含 Margin 概念这是应该理解的。Div 很优秀这不必说,然而当人们说 Div + CSS 的时候,似乎暗示着 Table 无法 CSS,这是天大的误会。
Div 支持的所有 CSS 属性,Table 全部支持,事实上,在 Div 大红大紫之前,那些 Div 的早期采用者曾信心不足地表示,Table 能做到,Div 都能,而他们也为自己的话付出了代价,企图在 Div 中实现垂直居中的人明白我的意思,企图在 IE6 中不经 CSS Hack 而实现 100% Div 布局的人更明白我的意思。100% Height 问题,几个 Div 之间的宽度自适应问题,相信任何从事 Div + CSS 设计的人会遇到。Table 在这方面的优势并不是因为它本身多么优秀,而是因为它老牌,没有浏览器敢忽视,也因为它的特性原本如此,人们发明表格,是因为希望数据显示得整齐,就这么简单。
然而,为什么 Table 后来背上那么多的恶名?Div 拥护者对 Table 的责难不外乎以下几条。
(1) 代码臃肿:你至少需要写下 <table><tr><td>这三个标签之后,才能开始真正的内容,另外,Table 的各种标签中还包含了复杂的属性定义,而 Div 只需 <div>一个标签。
(2) 页面渲染性能问题:浏览器需要将整个表格完全读完后才会开始渲染。
(3) 不利于搜索引擎优化:搜索引擎喜欢内容与修饰分开。
(4) 可访问性差:屏幕朗读软件和盲文浏览器无法很好地理解 Table 中的内容。
(5) 不够语义(Semantic):我们需要语义的 Web。
第1条:代码臃肿
首先,Table 里面唯一无法用 CSS 定义的属性只有 Cellspacing, Cellpadding 几个,其它属性都可以并且应当使用 CSS,这样,剩下的,就是 <table><tr><td> 和 <div> 的对决,我相信一个动辄几十K大小的网页,即使使用了几十个 Table,因此多出来的代码也可以忽略不计,那些埋怨 Table 代码臃肿的人其实该检查自己的编码习惯,能将 Table 写得十分臃肿的人,写 Div 相比也未必会简洁到哪里。
第2条:页面渲染性能问题
我使用一台2004年的笔记本电脑,1.6G 的 CPU 与 1G 内存,这种配置下,看不出 Table 布局和 Div 布局在页面渲染上有任何速度差别,其实这点差别即使有,相对网络本身的延迟也可以忽略。
第3条:不利于搜索引擎优化
如果你尽可能使用 CSS 而不是 Table 的属性,前面说了,产生的代码和 Div 的差别也不会很大,搜索引擎会歧视 <table> 标签吗,这种说法的依据我至今并没有找到。
第4条:可访问性差
这是 Table 固有的缺陷,不过多数 Div + CSS 的拥趸似乎并不是基于这个原因才排斥 Table。
第5条:不够语义
语义 Web 的含义要深远得多,并不是仅仅在 Table 和 Div 上纠缠,即使 W3C,也并没有规定 Table 只能用来显示表格数据,很多在 Table 的语义上进行纠缠的人,其实不妨再等等 HTML 5,那才是真正的语义。
本文的目的不是让你丢弃 Div 投身 Table,相反,如果 Div 能满足你的设计需要,Div 仍是首选,但没必要避讳 Table,否则会走入另外一个极端。很多使用 Div 无法简单实现的设计,仍可以使用 Table,当然,不管使用什么,都应该用 CSS 将内容与修饰分离。Div + CSS 和 Table + CSS 都是合法的设计,谁更简单就用谁。根据我的经验,当你能预见你的内容的格式,对你即将加入的内容有能力完全控制其显示格式时,应当使用 Div + CSS;当你即将加入的内容是不固定的,你无法预见其格式,如果不想让页面坍塌,使用 Table + CSS 是一种安全的做法。
W3C小组公布HTML5激动人心的特性
HTML基本思维概念形成于2003年,之后W3C对页面超文本应用技术工作小组(WHATWG)开发的HTML草图颇感兴趣,这个小组的开发人员均来自Apple ,Mozilla,和Opera。2007年W3C工作小组正式成立,主要进行HTML 5规格进行开发。目前开发仍在进行中,有望在2012年发布。
2009年4月10日星期五
跨frameset层的最新不完全实现[转]
无意中发现可以用这种方法实现跨frameset的层:
将层appendChild到frameset page的document.documentElement!
实现的浏览器仅限(已测):
FF3,Chrome,Safari,Netscape,Mozilla
测试代码:x.html
<html>
<head></head>
<body>
<script>
var maskTips = function(){
this.mask = null;
this.layer = null;
this.title = null;
this.content = null;
this.cssMask = 'position:absolute;left:0;top:0;width:100%;height:100%;overflow:hidden;background:#000;-moz-opacity:0.6;opacity:0.6;filter:alpha(opacity=60);z-index:100;border:none;';
this.cssLayer = 'position:absolute;left:30%;top:35%;width:300px;height:150px;background:white;border:5px solid #ddd;z-index:102;padding:0;';
};
maskTips.prototype = {
init:function(){
var xdom = (top.document)?top.document:document;
alert(xdom.documentElement);
var xdoc = xdom.createDocumentFragment();
this.mask = xdom.createElement('div');
this.mask.innerHTML = '<iframe src="about:blank" style="width:100%;height:100%;-moz-opacity:0;opacity:0;filter:alpha(opacity=0);"></iframe>';
this.layer = xdom.createElement('div');
this.layer.innerHTML = '<div style="background:#ddd;border-bottom:5px solid #ddd;text-align:right;overflow:hidden;zoom:1;"><h3 style="float:left;margin:0;padding:0;">title</h3><button style="font-size:12px;">X</button></div><div style="padding:5px;">content</div><div class="tips-bd"></div><div class="tips-ft"></div>';
this.mask.style.cssText = this.cssMask;
this.layer.style.cssText = this.cssLayer;
xdoc.appendChild(this.mask);
xdoc.appendChild(this.layer);
this.title = this.layer.childNodes[0];
this.content = this.layer.childNodes[1];
xdom.documentElement.appendChild(xdoc);
xdom = xdoc = null;
}
};
var x = new maskTips();
x.init();
</script>
</body>
</html>
测试代码:y.html
<html>
<head></head>
<frameset rows="300,*">
<frame src="x.html"></frame>
<frame src="http://www.v-ec.com/dh20156/article.asp?id=204"></frame>
</frameset>
</html>
2009 CSS Naked Day - 2009网页裸奔节
CSS Naked Day 的来历
CSS Naked Day,也称CSS裸奔节或CSS裸奔日,
在裸奔节这天,参加裸奔节的Blog 将会去除页面上所有的 CSS 样式和广告裸奔整整一天,通过这个节日来重视CSS的重要性.当然你的网站如果是用table来布局的话这个节日对你来说并不是很合适.在2006年有将近800个国际知名网站参与这个节日.
CSS Naked Day 的目的
推动Web标准、提倡简洁为美、使用正确的 (x)html语义标记、良好的层次结构。暂时把页面设计抛弃,直接展示<body>内容!
历届CSS Naked Day的举办时间
第一届CSS裸奔节:2006年4月5日
第二届CSS裸奔节:2007年4月5日
第三届CSS裸奔节:2008年4月9日
第四届CSS裸奔节:2009年4月9日
如何加入CSS Naked Day
使用如下的PHP代码
<?php
function is_naked_day($d) {
$start = date('U', mktime(-12, 0, 0, 04, $d, date('Y')));
$end = date('U', mktime(36, 0, 0, 04, $d, date('Y')));
$z = date('Z') * -1;
$now = time() + $z;
if ( $now >= $start && $now <= $end ) {
return true;
}
return false;
}
?>
在你的head头文件中这样调用
<head>
...
<?php
if ( is_naked_day(9) ) {
echo '<!-- naked day has no styles -->';
} else {
echo '<link rel="stylesheet" type="text/css" href="styles.css" />';
}
?>
...
</head>
2009年4月9日星期四
网页设计中CSS十大注意事项
当使用css定义字体时你可能会这样做:
| font-size: 1em; line-height: 1.5em; font-weight: bold; font-style: italic; font-variant: small-caps; font-family: verdana,serif; |
font: 1em/1.5em bold italic small-caps verdana,serif
现在好多了吧,不过有一点要注意:使用这一简写方式你至少要指定font-size和font-family属性,其他的属性(如font-weight, font-style,font-varient)如未指定将自动使用默认值。
2.同时使用两个class
通常我们只为属性指定一个class,但这并不等于你只能指定一个,实际上,你想指定多少就可以指定多少,例如:
通过同时使用两个class(使用空格而不是逗号分割),这个段落将同时应用两个class中制定的规则。如果两者中有任何规则重叠,那么后一个将获得实际的优先应用。
3.css中边框(border)的默认值
当编写一条边框的规则时,你通常会指定颜色、宽度以及样式(任何顺序均可)。例如:border: 3px solid #000(3像素宽的黑色实线边框),其实这个例子中唯一需要指定的值只是样式。假如你指定样式为实线(solid),那么其余的值将使用默认值:默认的宽度为中等(相当于3到4像素);默认的颜色为边框里的文字颜色。如果这正是你想要的效果,你完全可以不在css里指定。
4.!important会被IE忽略
在css中,通常最后指定的规则会获得优先权。然而对除了IE以外的浏览器来说,任何后面标有!important的语句将获得绝对的优先权,例如:
margin-top: 3.5em !important; margin-top: 2em
除IE以外所有浏览器中的顶部边界都是3.5em,而IE为2em,有时候这一点很有用,尤其在使用相对边界值时(就像这个例子),可以显示出IE与其他浏览器的细微差别。
(很多人可能还注意到了css的子选择器也是会被IE忽略的)
5.图片替换的技巧
使用标准的html而不是图片来显示文字通常更为明智,除了加快下载还可以获得更好的可用性。但是如果你决心使用访问者的机器中可能没有的字体时,你只能选择图片。
举例来说,你想在每一页的顶部使用“Buy widgets”的标题,但你同时又希望这是能被搜索引擎发现的,为了美观你使用了少见的字体那么你就得用图片来显示了:
这样当然没错,但是有证据显示搜索引擎对真实文本的重视远超过alt文本(因为已经有太多网站使用alt文本充当关键字),因此,我们得用另一种方法: <h1><span>Buy widgets</span></h1>,那你的漂亮字体怎么办呢?下面的css可以帮上忙:
| h1 { background: url(widget-image.gif) no-repeat; } h1 span { position: absolute; left:-2000px; } |
6.css盒模型hack的另一选择
css盒模型hack被用来解决IE6之前的浏览器显示问题,IE6.0之前的版本会把某元素的边框值和填充值包含在宽度之内(而不是加在宽度值上)。例如,你可能会使用以下css来指定某个容器的尺寸:
| #box { width: 100px; border: 5px; padding: 20px; } |
盒的总宽度在几乎所有浏览器中为150像素(100像素宽度 两条5像素的边框 两个20像素的填充),唯独在IE6之前版本的浏览器中仍然为100像素(边框值和填充值包含在宽度值中),盒模型的hack正是为了解决这一问题,但是也会带来麻烦。更简单的办法如下:
| css: #box { width: 150px; } #box div { border: 5px; padding: 20px; } html: ... |
这样一来在任何浏览器中盒的总宽度都将是150像素。
7.将块元素居中假设你的网站使用了固定宽度的布局,所有的内容置于屏幕中央,可以使用以下的css:
| #content { width: 700px; margin: 0 auto; } |
| body { text-align: center; } #content { text-align: left; width: 700px; margin: 0 auto; } |
8.使用css实现垂直居中
垂直居中对表格来说是小菜一碟,只需指定单元格为vertical-align: middle即可,但这在css布局中不管用。假设你将一个导航菜单的高度设为2em,然后在css中指定垂直对齐的规则,文字还是会被排到盒的顶部,根本没有什么区别。
要解决这一问题,只需将盒的行高设为与盒的高度相同即可,以这个例子来说,盒高2em,那么只需在css中再加入一条:line-height: 2em 就可实现垂直居中了!
9. 容器内的css定位
css的最大优点之一就是可以将对象定位在文档的任何位置,同样的也可以将对象在某容器内进行定位。只需要为该容器添加一条css规则:
| #container { position: relative; } |
如果想将navigation定位在容器内离左边界30像素,离顶部5像素,可以使用以下css语句:
| #navigation { position: absolute; left: 30px; top: 5px; } |
10.延伸至屏幕底部的背景色
css的缺点之一是缺乏垂直方向的控制,从而导致了一个表格布局不会遇到的问题。假设你在页面的左侧设定了一列用于放置网站的导航。页面为白色背景,但你希望导航所在的列为蓝色背景,使用以下css即可:
| #navigation { background: blue; width: 150px; } |
| body { background: url(blue-image.gif) 0 0 repeat-y; } |
到写这篇文章为止这是对这类问题的唯一解决办法,因此你只能为左列使用像素值来获得能够自动延伸的不同的背景色

