代码改变世界

javascript学习总结之(事件,函数等)

2009-09-27 11:33  key_sky  阅读(644)  评论(0编辑  收藏  举报

一.Document

Code
<head runat="server">
    
<title>Document对象</title>
    <script type="text/javascript">
        
//***************************************************Summary*****************************************
        //write():从javascript程序中动态生成网页的内容
        //writeln():方法与write相同,不过在输出的参数之后自动加上换行符
        //***************************************************End*********************************************
        function onSubmit() {
            
var date = new Date();
            document.write(
'<p>Document Loaded on:' + date.toLocaleTimeString());
            document.write(
'<br>Document modified on:' + document.lastModified);
            
//document一旦被解析,文档将被覆盖,包括处理程序。
        }
    
</script>
</head>
<body>
    
<form id="form1" runat="server">
    
<input id="Button1" type="button" value="SubmitTime" onclick="onSubmit()" />
    <input type="button" value="Start" onclick="onStartClick()" />
    <input type="button" value="Stop" onclick="onEndClick()" />
    <img id="animation" src="Image/1.gif" alt="Animation Effect" />
    <script type="text/javascript">
        
var aniframe = new Array(10);
        
var frame = 0//帧计数器:跟踪当前的帧
        var timeout_id = null//允许我们用clearTimeout()方法停止动画  
        //函数将执行动画
        function animate() {
            frame 
= (frame + 1% 10//更新计数器
            document.getElementById('animation').src = 'Image/' + frame + '.gif'//重新制定图片url 
            timeout_id = setTimeout("animate()"1000); //播放下一帧
        }
        
function onStartClick() {
            
if (timeout_id == null) animate();
        }
        
function onEndClick() {
            
if (timeout_id) {
                clearTimeout(timeout_id);
                timeout_id 
= null;
            }
        }
    
</script>
    </form>
</body>

运行效果:点击SubmitTime按钮

Document Loaded on:11:11:48
Document modified on:09/27/2009 11:11:48

点击Start按钮:图片顺序播放,点击Stop,播放停止。

二.Dom树

Code
<head runat="server">
    
<title>Dom对象</title>
     <script type="text/javascript">
        
//***************************************************Summary*****************************************
         //Dom树由Node组成,Node对象的childNodes属性将返回子节点的列表,firstChild,lastChild,nestSibling,
         //previousSibling和parentNode属性提供了遍历树的方法。appendChild(),removeChild(),replaceChild和
         //insertBefore()方法能给文档树添加节点或从文档树中删除节点。
         //Dom子节点的类型由nodeType值确定
         //接口                                nodeType值
         //Element                                 1
         //Text                                    3
         //Document                                9
         //Comment                                 8
         //DocumentFragment                        11
         //Attr                                    2
         //获取Dom元素:document.getElementById(element),document.getElementByName;
         //***************************************************End*********************************************
         function onClickReverseDom() {
             
for (index = document.body.childNodes.length - 1; index >= 0; index--) {
                 
var c = document.body.removeChild(document.body.childNodes[index]);
                 document.body.appendChild(c);
             }
         }
         
function onClickUpperDom() {
             UpperDom(document.getElementById(
'p1'));
         }
         
function UpperDom(n) {
             
//判断为textnode
             if (n.nodeType == 3) {
                 
var newNode = document.createTextNode(n.data.toUpperCase());
                 
var parent = n.parentNode;
                 parent.replaceChild(newNode, n);
             }
             
else {
                 
for (var i = 0; i < n.childNodes.length; ++i) UpperDom(n.childNodes[i]);
             }
         }
    
</script>
</head>
<body>
    
<p id="p1">paragraph #1</p>
    <p id="p2">paragraph #2</p>
    <p id="p3">paragraph #3</p>
    <input id="btnReverse" type="button" value="Reverse Dom" onclick="onClickReverseDom()" />
    <input id="btnUpperDom" type="button" value="Upper Dom" onclick="onClickUpperDom()" />
</body>

运行效果:点击Reverse Dom按钮:所有Dom树倒序加载。点击Upper Dom选定的元素变成大写:PARAGRAPH #1

三.事件处理程序

//***************************************************Summary*****************************************
        //原始事件模型
        //处理程序                   触发机制
        //onabort                    图像装载被中断
        //onblur                     元素失去输入焦点
        //onchage                    元素文本改变
        //onclick                    鼠标按下并释放在mouseup事件后触发
        //ondbclick                  双击鼠标
        //onerror                    装载图像的过程中发生了错误
        //onfocus                    元素得到输入焦点
        //onkeydown                  键盘被按下。返回false取消默认动作
        //onkeypress                 键盘键被释放返回false取消默认动作
        //onkeyup                    键盘键被释放
        //onload                     文档装载完毕
        //onmousemove                鼠标移动
        //onmouseout                 鼠标离开元素
        //momouseover                鼠标移到元素上。对于链接元素,返回true防止url出现在状态栏
        //onmouseup                  释放鼠标键
        //onreset                    表单请求重置。返回false阻止重置
        //onresize                   调整窗口大小
        //onselect                   选中文本
        //onsubmit                   请求提交表单。返回false阻止提交
        //onunload                   卸载文档或框架集
        //***************************************************End*********************************************

四.表单验证

Code
<head runat="server">
    
<title>Form验证</title>
    <script type="text/javascript">
        
//***************************************************Summary*****************************************
        //onclick,onchange,onblur(失去焦点时触发),onfocus(聚焦时触发)
        //按钮以及text元素忽略
        //Select元素表示用户可以选择的选项,由Option元素集合(options[]),selectedIndex属性获取选中项的集合
        //selected返回该Option是否选中,注意select元素某一option清空后,后一元素将自动往前移动
        //***************************************************End*********************************************
        //空字符以及回车检索
        function isblank(s) {
            
for (var index = 0; index < s.length; ++index)
                
var chr = s.charAt(index);
            
if (chr == nullreturn false;
            
if ( chr.toString().trim() != '' && chr != '\n'return false;
            
return true;
        }
        
//表单验证
        function vertify(f) {
            
var msg;
            
var empty_fields = "";
            
var errors = "";
            
for (var index = 0; index < f.length; ++index) {
                
var e = f.elements[index];
                
if (((e.type == 'text'|| (e.type == 'textarea')) && !e.optional) {
                    
//检索空
                    if (e.value == null || isblank(e.value)) {
                        empty_fields 
+= "\n    " + e.name;
                        
continue;
                    }

                    
//检索数字
                    if (e.numeric || (e.min != null|| (e.max != null)) {
                        
var v = parseFloat(e.value);
                        
if (isNaN(v) || ((e.min != null&& (v < e.min)) || ((e.max != null&& (v >
                        e.max))) {
                            errors 
+= "- The field" + e.name + " must be number";
                            
if (e.min != null) errors += " that is greater than " + e.min;
                            
if (e.man != null) errors += " and less than " + e.max;
                            
else if (e.max != null) errors += " that is less than " + e.max;
                            errors 
+= " ,\n";
                        }
                    }
                }
            }
            
if (!empty_fields && !errors) return true;
            msg 
= '_______________________________________________________________________________________________ _\n\n';
            msg 
+= 'The form was not submit successfully because of the following errors(s)' + errors + '.\n';
            msg 
+= 'Please correct these error(s) and submit again.\n';
            msg 
+= '______________________________________________________________________________________________ _\n\n';
            
if (empty_fields) {
                msg 
+= ' The following required field(s) are empty:' + empty_fields + '\n';
            }
            alert(msg);
            
return false;
        }
    
</script>
</head>
<body>
    
<form id="form1" runat="server" onsubmit="this.firstname.optional=true;this.phonenumber.optional=true;
    this.zip.min=0;this.zip.max=99999;return vertify(this);
">
    First name:
<input type="text" name="firstname"/>
    Last name:<input type="text" name="lastname"/><br />
    Address:
<br/><textarea name="address" rows="4" cols="40"></textarea><br />
    Zip Code:<input type="text" name="zip"/><br />
    Phone Number:
<input type="text" name="phonenumber"/>
    <input type="submit" />
    </form>
</body>

五.浏览器属性读取

Code
<head runat="server">
    
<title>Navigator</title>
    <script type="text/javascript">
        
//****************************Summary***********************************
        //appName:web浏览器的简单名称
        //appVersion:浏览器版本号
        //userAgent:浏览器在它的USER-AGENT HTPP标题中发送的字符串
        //appCodeName:浏览器的代码名
        //platform:运行浏览器的硬件平台
        //****************************End***************************************
        function onGetNavigatorInfo() {
            
var browser = "Browser Information:\n";
            
for (var propname in navigator) {
                browser 
+= propname + "" + navigator[propname] + "\n";
            }
            alert(browser);
            alert(
"浏览器名称:" + navigator.appName);
            alert(
"浏览器版本:" + parseInt(navigator.appVersion));
        }
    
</script>
</head>
<body>
    
<form id="form1" runat="server">
    
<input id="Button1" type="button" value="GetNavigatorInfo"  onclick="onGetNavigatorInfo()"/>
    </form>
</body>

六.Winodw对象操作

Code
<head runat="server">
    
<title>Window对象控制方法</title>
    <script type="text/javascript">
        
//**********************************************Summary*******************************
        //open():第一个参数是文档的url,可以为空,第二个参数是新打开窗口的名字,第三个参数为窗口
        //的特性,例如窗口大小和GUI修饰
        //close():窗口关闭
        //scrollBy():窗口中显示的文档向左,向右或者向上、向下滚动指定数量的像素
        //scrollTo():文档滚动到一个绝对位置
        //**********************************************End***********************************
        var win;
        
function OnOpenUrlClick() {
            win 
= window.open('',''"width=200,height=200,status=yes,resizable=yes");
            win.moveTo(
200200); //设置窗口的初始位置
            window.setInterval('MoveWindow()'1000);
        }
        
function MoveWindow() {
            
if (win.closed) clearInterval(1000); return;//窗口关闭返回
            var x = 0, y = 0, dx = 5, dy = 5;
            
if ((x + dx > (screen.availWidth - 200)) || (x + dx < 0)) dx == -dx;
            
if ((y + dy > (screen.availHeight - 200)) || (y + dy < 0)) dy == -dy;
            
//到达边界就弹回
            //更新窗口当前位置
            x += dx;
            y 
+= dy;
            
//移动窗口
            win.moveTo(x, y);
        }
    
</script>
</head>
<body>
    
<form id="form1" runat="server">
    
<input id="Button1" type="button" value="打开新窗口" onclick="return OnOpenUrlClick()" />
    </form>
</body>

点击按钮,窗体自动移动。

七.Window方法调用

Code
<head runat="server">
    
<title>Window Object</title>
    <script type="text/javascript">
        
//*********************************Summary********************************************************
        //alert(),confirm(),prompt()想用户显示简单的对话框,confirm()和prompt()用于获取用户的相应
        //close()关闭窗口
        //focus(),blur():请求或放弃窗口的键盘焦点。
        //moveBy(),moveTo():移动窗口。
        //print()打印窗口或框架中的内容
        //resizeBy(),resizeTo():调整窗口大小
        //scrollBy(),scrollTo():滚动窗口中显示的文档。
        //setInterval(),clearInterval():设置或取消重复调用的函数,该函数在两次调用之间有特定的延迟。
        //setTimeout(),clearTimeout():设置或者取消在制定的若干毫秒后要调用一次的函数
        //*********************************End************************************************************
        function alertclick() {
            alert(
'Hello Javascript');
        }
        
function confirmclick() {
            
if (confirm('Load The Script')) {
                alert(
'Script Loaded');
            }
            
else {
                setTimeout(
"alertFailed()"3000);
            }
        }
        
function alertFailed() {
            alert(
'Script is Loading');
        }
        
function promptclick()
        {
            
var n = prompt("Wellcome to the world of Javascript""");
            alert(n 
+ " Hello World");
        }
        
function ShowNowDateTime() {
            
var d = new Date();
            
var time = d.toLocaleDateString() + "|" + d.toLocaleTimeString();
            div1.innerHTML 
= time;
            defaultStatus 
= time;//状态栏显示
            setTimeout("ShowNowDateTime()"1000);
        }
        
function AlertWindow() {
            alert(
'欢迎再次浏览');
        }
        
//窗体关闭
    </script>
    <style type="text/css">
        #div1
        {
            width: 351px;
            height: 30px;
            color:Red;
            border:
2;
            background
-color:Green;
        }
    
</style>
</head>
<body onload="ShowNowDateTime()" onunload="AlertWindow()">
    
<form id="form1" runat="server">
    
<div>
        
<input id="Button1" type="button" value="alert" onclick="alertclick()" />
        <input id="Button2" type="button" value="confirm" onclick="confirmclick()" />
        <input id="Button3" type="button" value="prompt" onclick="promptclick()" />
    </div>
    <div id="div1" ></div>
    </form>
</body>

八.Cookie

Code
<head runat="server">
    
<title>Cookie</title>
     <script type="text/javascript">
        
//***************************************************Summary*****************************************
         //cookie对象包括名字、值、生存期、可见性、安全性。cookie值得不能含有分号、逗号或空白符,存入时使用
         //escape()函数将对象值进行编码,读取时用unescape()进行解码,每个cookie保存数据不能超过4K字节
         //expires:指定cookie的生存期
         //store():遍历cookie对象的所有由用户定义的属性,并将这些属性的名称和值连接到一个字符串
         //***************************************************End*********************************************
         //构造函数:用指定的名字和可选的性质为指定的文档创建一个cookie对象
         //document:保存cookie的document对象。
         //name:指定cookie名的字符串。
         //hours:指定从现在起cookie过期的小时数
         //path:指定了cookie的路径性质
         //domain:指定cookie的域性质
         //secure:确定是否需要一个安全的cookie。true 和false
         function Cookie(document, name, hours, path, domain, secure) {
             
this.$document = document;
             
this.$name = name;
             
if (hours) this.$expiration = new Date((new Date()).getTime() + hours * 3600000);
             
else this.$expiration = null;
             
if (path) this.$path = path; else this.$path = null;
             
if (domain) this.$domain = domain; else this.$domain = null;
             
if (secure) this.$secure = trueelse this.$secure = false;
         }
         
//cookie对象的store()
         Cookie.prototype.store = function() {
             
//遍历cookie对象,并将cookie值连接起来,cookie将等号和分号做为分隔符.
             //获取完毕对每个状态变量值进行转义
             var cookieval = '';
             
for (var prop in this) {
                 
//忽略所有名字以$开头的属性和方法
                 if ((prop.charAt(0== '$'|| ((typeof this[prop]) == 'function')) continue;
                 
if (cookieval != '') cookieval += '&';
                 cookieval 
+= prop + ':' + escape(this[prop]);
             }
             
var cookie = this.$name + '=' + cookieval;
             
if (this.$expiration) cookie += ';expires=' + this.$expiration.toGMTString();
             
if (this.$path) cookie += ';path=' + this.$path;
             
if (this.$domain) cookie += ';domain=' + this.$domain;
             
if (this.$secure) cookie += ';secure';
             
//设置Document.cookie属性保存cookie
             this.$document.cookie = cookie;
         }
         
//cookie对象的load()
         Cookie.prototype.load = function() {
             
//读取cookie列表
             var allcookies = this.$document.cookie;
             
if (allcookies == ''return false;
             
var start = allcookies.indexOf(this.name + '=');
             
if (start == -1return false//未定义cookie;
             start += this.$name.length + 1//跳过名字和等号
             var end = allcookies.indexOf(';', start);
             
if (end == -1) end = allcookies.length;
             
var cookieval = allcookies.substring(start, end);

             
var a = cookieval.split('&'); //分割成名字/值对
             for (var i = 0; i < a.length; i++) a[i] = a[i].split(':'); //值存入数组
             for (var i = 0; i < a.length; i++) {
                 
this[a[i][0]] = unescape(a[i][1]);
             }
             
return true;
         }
         
//coolie的remove()
         Cookie.prototype.remove = function() {
             
var cookie;
             cookie 
= this.$name + '=';
             
if (this.$path) cookie += '"path=' + this.$path;
             
if (this.$domain) cookie += ';domain=' + this.$domain;
             cookie 
+= ';expires=Fri,02-Jan-1970 00:00:00 GMT';
             
this.$document.cookie = cookie;
         }

         
//****************************Samples*************************
         var visitordata = new Cookie(document, "name_color_count_state"240);
         
//读取cookie存储数据,未符合要求则向用户查询数据
         if (!visitordata.load() || !visitordata.name || !visitordata.color) {
             visitordata.name 
= prompt('What is your name:''');
             visitordata.color 
= prompt('What is your favoriate color:''');
         }
         
//跟踪用户访问页面次数
         if (visitordata.visits == null) visitordata.visits = 0;
         visitordata.visits
++;
         
//保存cookie
         visitordata.store();

         document.write(
'<font size="7" color="' + visitordata.color + '">' + 'wellcome,' +
         visitordata.name 
+ '!</font>' + '<p>You have visited ' + visitordata.visits + ' times.');
              
</script>
</head>
<body>
    
<form id="form1" runat="server">
    
<input type="button" value="Forget My Name" onclick="visitordata.remove()" />
    </form>
</body>