注    册
密 码 忘记密码
保存密码         取消

个人资料

昵称: blogzb
姓名: 张滨
性别:
生日: 1980-1-1
星座: 水瓶座
学历: 学士
院校:
行业: 政府机关
头衔: 技术人员/工程师
位置: 中国-黑龙江-哈尔滨
家乡: 中国-黑龙江-哈尔滨
个人标签:
个人简介:
自己看吧!~
座右铭:
爱咋咋地!~

详细资料..

图片

我的相册

2006-02-09 10:05:31

5张照片

更多图片..

最新评论

日志

不错的BLOG

分类:jsp

http://blog.csdn.net/pengpenglin/category/172885.aspx

让处于contentEditable=true的层里面的图片响应键盘事件

分类:AJAX

让处于contentEditable=true的层里面的图片响应键盘事件

http://www.webjx.com  更新日期:2005-09-16  网页教学网  浏览次数: 176

border=0 align=center marginWidth=0 marginHeight=0 src="http://www.webjx.com/ad/article_ad.htm" frameBorder=no width=486 scrolling=no height=60>
<SCRIPT LANGUAGE=javascript FOR=document EVENT=onkeyup>
ku()
</SCRIPT>
<div id="eee" >
<img src="http://www.google.com/images/logo_sm.gif">asdfasdfasdfas
<input type="text" value="aa">adfasdf
</div>
<script language="javascript">
eee.contentEditable=true

document.onkeyup=kd()
function ku(){
var oControlRange = document.selection.createRange();
if (oControlRange(0).tagName.toUpperCase() == "IMG") {
alert("您在图片上按了键!")
}
}
</script>

javascript and flash communication

分类:flash

目录:

FS Command命令简介
对FS Command命令的支持
通讯的两个方向
怎样实现Flash 到 JavaScript的通讯
怎样实现JavaScript 到 Flash 的通讯
可取的 Flash JavaScript方法(未译)
相关内容参考(未译)


FS Command命令简介

本文写作的目的就是主要用“fscommand”函数探讨Flash与JavaScript之间的通讯的问题(Flash在Web浏览器中执行JavaScript声明)。但是,fscommand()函数的功能实际上要比这些强大得多。不用太多的细节描述,以下是fscommand()函数简短的概述:

“fscommand()”是Flash中一个函数的名字,它提供Flash 应用程序的通讯功能(“应用程序”的意思是任何可以播放Flash媒体的工具,无论是自然的,例如标准的独立的Flash Player播放器;还是插件的使用,例如Web浏览器)。例如,基于Web的fscommand()函数可以响应Flash按钮的click事件,执行JavaScript命令。(一会我们将看到JavaScript也可以控制Flash影片的回放功能)。Fscommand()函数也可以和Lingo语言通讯,并且也可以发送内建的命令集到Flash Player播放器中(例如“Quit”,“FullScreen”,“AllowScale”,“ShowMenu”)。


对FS Command命令的支持

好了,让我们回到主题:在Web中使用fscommand()函数。如果你打算为Web开发带有脚本的Flash影片,你必须意识到不是所有的浏览器都支持fscommand()函数。支持该函数的特殊浏览器有:

·netscape 3 or 4 on win95/98/nt and mac ppc
·internet explorer 3 and greater on win95/98/nt
·netscape 6.2 (and later) running flash player 6.0.40.0 (and later)

特殊的不支持fscommand()函数的浏览器有:

·运行在 windows 3.1上的浏览器
·运行在 macintosh 68k 机器上的浏览器
·任何在Mac上运行的IE
·netscape 6.1 和 6.0 运行 flash player 6.0.29.0 或者比较老的版本 (liveconnect 属性不支持mozilla遗留下来的插件。 使用mozilla需要更新插件,可以到这里去更新插件 mozilla plugin api). 察看 bugs 37710 和 18838.

不支持的浏览器缺少Active X(IE)或者LiveConnect(Netscape 4和更老的版本),要实现在插件和浏览器之间的通讯这些是必需的。此外,对于Flash 3,如果你正为Netscape 4开发包含fscommand 的Flash内容,你需要在每个页面明确的使用LiveConnect来管理包含脚本的Flash影片(你不必在Netscape 6.2和以后的版本使用LiveConnect)。对于支持LiveConnect的浏览器,应把这一属性包含在你的影片的EMBED 标签中,例如 swLiveConnect = “true”。 在执行的过程中,用户将在Netscape状态栏中看到 ”Starting Java…”,并且当Java加载时要等待一会。


通讯的两个方向

那么现在,我们知道了在哪里可以使用fscommand函数的功能;你也许想知道它是怎样工作的。我们首先检测基于fscommand功能的Flash到JavaScript的通讯。然后,我们将再看看发送信息的另一种方法:JavaScript到Flash的通讯。


怎样实现Flash 到 JavaScript的通讯

(在研究用fscommand()函数执行JavaScript代码之前,应该注意的是JavaScript也可以通过getURL()函数来调用,就象用锚标记<A>调用JavaScript一样)。GetURL()函数与fscommand()函数相比,会获得更广泛的浏览器的支持,暂且不提它为编码带来的便利。要了解更多的信息,参考用JavaScript调用getURL函数来开启一个窗口。现在让我们回到对fscommand()函数的讨论中)。

无论fscommand()函数是否执行,Flash都试图发送消息给JavaScritp。当浏览器收到一个来自Flash的fscommand命令,它会检测:是否存在一个与之匹配的JavaScript函数(或者IE浏览器中VB Script函数),该函数可以“捕获”fscommand命令。如果存在这样的函数,浏览器将执行这个“捕获”函数,并且发送两个参数给这个函数——这两个参数就是fscommand() 函数中“Command”和“Arguments”参数。

如下所示得图表图解了这个过程,该范例用fscommand()函数来调用JavaScript警告框。Fscommand的参数是”call_alert”和”Hello world!”,

如下所示:

fscommand(“call_alert”, “Hello world!”);

执行这个fscommand命令在Netscape和IE中有略微不同;下面的图示显示了该命令在两个浏览器中的传递(从Flash到JavaScript)。图示下面是相应的Flash范例,看看这个模型,我们接来就分析实现这一功能的细节。

观看演示

FS Command影片范例:Flash调用JavaScript警告框



让我们一起完成如上图所示的Flash调用JavaScript的FS Command方法。你可以下载这个范例1的Zip文件,它包括.fla,.swf和.html格式文件。具体操作如下(请注意:以下操作均在 Flash MX Professional 2004中进行):



1)在Flash中建立FS Command语句:



·新建一个影片,在时间线上开始的几桢上随意设置一个关键桢;



·选中该关键桢,按F9,打开动作面板;



·在动作面板中点击“动作”下面的“+”按钮,选择“全局函数”---“浏览器/网络”---fscommand()函数。然后,“fscommand”命令便加入到动作列表中。该函数参数包括两个部分“Command”和“Arguments”。这两个参数将被传递到JavaScript的“fscommand捕获”函数中。它们可以用在任何条件下,但是通常情况下,Command参数包含一个你想执行的函数名称;Arguments参数包含你提供的参数;



·在括号中输入“"call_alert", "Hello world!"”;



2)把你的影片嵌入到HTML文档中:



为你的影片建立一个HTML文档,并且使用OBJECT 和EMBED标记放置你的影片。在OBJECT 和EMBED标记中,确定你影片的名字,为OBJECT标记使用”ID”,为EMBED标记使用”NAME”。影片的名字是非常重要的,因为这个名字将被OBJECT 和EMBED标记识别出来。你的FS Command捕获函数将依靠影片的名字来识别所有捕获的FS Command命令。另外要记住的是对于Netscape浏览器的LiveConnect参数用“swLiveConnect = “true””来替换。你的页面应该象下面这样(ID、NAME和swLiveConnect都加粗了,不要忘记它们):



<HTML>

<HEAD>

<TITLE>My First FS Command</TITLE>

</HEAD>



<BODY>



<OBJECT

CLASSID="clsid : D27CDB6E-AE6D-11cf-96B8-444553540000"

WIDTH="100%"

HEIGHT="100%"

CODEBASE="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0"

ID=testmovie>

<PARAM NAME="MOVIE" VALUE="mymovie.swf">

<PARAM NAME="PLAY" VALUE="true">

<PARAM NAME="LOOP" VALUE="true">    

<PARAM NAME="QUALITY" VALUE="high">

<PARAM NAME="SCALE" VALUE="SHOWALL">



<EMBED

NAME="testmovie"

SRC="mymovie.swf"

WIDTH="100%"

HEIGHT="100%"

PLAY="false"

LOOP="false"

QUALITY="high"

SCALE="SHOWALL"

swLiveConnect="true"

PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">

</EMBED>

</OBJECT>

</BODY>

</HTML>



3)为IE浏览器加入VB Script代码:



还记得在图示1中的第2个场景吗?IE浏览器使用很小的VB Script代码来捕获fscommand命令,然后把它传递给JavaScript。这就是接下来你要做的。把如下的VB Script代码放在HTML文档的HEAD标记内,确定把文字“testmovie”改为你在OBJECT 和EMBED标记为你的影片起的名字。



<SCRIPT LANGUAGE="VBScript">

<!--

// Catch FS Commands in IE, and pass them to the corresponding JavaScript function.



Sub testmovie_FSCommand(ByVal command, ByVal args)

call testmovie_DoFSCommand(command, args)

end sub



// -->

</SCRIPT>



4)加入JavaScript函数来捕获fscommand命令:



到目前为止,我们已经建立了影片,它可以发送fscommand命令到浏览器上;影片也已经被嵌入到HTML页面中,也建立了VB Script代码,它可以为JavaScript捕获fscommand命令——如果你的浏览器是IE的话。把如下的JavaScript代码放到HEAD标记中,确定把文字“testmovie” 改为你在OBJECT 和EMBED标记为你的影片起的名字。



<SCRIPT LANGUAGE="JavaScript">

<!--

function testmovie_DoFSCommand(command, args) {

if (command == "call_alert") {

alert("Here's the Flash message: " + args);

}

}

//-->

</SCRIPT>



对于JavaScript的一点解释。“testmovie_DoFSCommand”函数随时调用名称为“testmovie”的发送fscommand命令的影片。“DoFSCommand” 关键字是Flash用来识别的函数,该函数被fscommand命令加载。前缀“testmovie_”指出被命令调用的影片的名称。因此,当一个名为“testmovie”的影片调用FS Command命令时,名为“testmovie_DoFSCommand”的函数将被加载。“(command, args)”是传递给函数的两个参数,并传送我们在Flash动作面板输入的 “Command”和“Arguments”的参数值——“call_alert”和“Hello world!”



一旦你的JavaScript函数放置好了,你的FS Command函数就可以成功的加载警告框了。

[JS]详尽解析window.event对象

分类:AJAX

[JS]详尽解析window.event对象



event代表事件的状态,例如触发event对象的元素、鼠标的位置及状态、按下的键等等。

event对象只在事件发生的过程中才有效。

event的某些属性只对特定的事件有意义。比如,fromElement 和 toElement 属性只对 onmouseover 和 onmouseout 事件有意义。

例子

下面的例子检查鼠标是否在链接上单击,并且,如果shift键被按下,就取消链接的跳转。

<HTML>
<HEAD><TITLE>Cancels Links</TITLE>
<SCRIPT LANGUAGE="JScript">
function cancelLink() {
if (window.event.srcElement.tagName == "A" && window.event.shiftKey)
window.event.returnValue = false;
}
</SCRIPT>
<BODY onclick="cancelLink()">

下面的例子在状态栏上显示鼠标的当前位置。

<BODY onmousemove="window.status = 'X=' + window.event.x + ' Y=' + window.event.y">

属性:

altKey, button, cancelBubble, clientX, clientY, ctrlKey, fromElement, keyCode, offsetX, offsetY, propertyName, returnValue, screenX, screenY, shiftKey, srcElement, srcFilter, toElement, type, x, y

--------------------------------------------------------------------------------

1.altKey
描述:
检查alt键的状态。

语法:
event.altKey

可能的值:
当alt键按下时,值为 TRUE ,否则为 FALSE 。只读。

2.button
描述:
检查按下的鼠标键。

语法:
event.button

可能的值:
0 没按键
1 按左键
2 按右键
3 按左右键
4 按中间键
5 按左键和中间键
6 按右键和中间键
7 按所有的键

这个属性仅用于onmousedown, onmouseup, 和 onmousemove 事件。对其他事件,不管鼠标状态如何,都返回 0(比如onclick)。

3.cancelBubble
描述:
检测是否接受上层元素的事件的控制。

语法:
event.cancelBubble[ = cancelBubble]

可能的值:
这是一个可读写的布尔值:

TRUE 不被上层原素的事件控制。
FALSE 允许被上层元素的事件控制。这是默认值。

例子:
下面的代码片断演示了当在图片上点击(onclick)时,如果同时shift键也被按下,就取消上层元素(body)上的事件onclick所引发的showSrc()函数。

<SCRIPT LANGUAGE="JScript">
function checkCancel() {
if (window.event.shiftKey)
window.event.cancelBubble = true;
}
function showSrc() {
if (window.event.srcElement.tagName == "IMG")
alert(window.event.srcElement.src);
}
</SCRIPT>
<BODY onclick="showSrc()">
<IMG onclick="checkCancel()" src="/sample.gif">

4.clientX
描述:
返回鼠标在窗口客户区域中的X坐标。

语法:
event.clientX

注释:
这是个只读属性。这意味着,你只能通过它来得到鼠标的当前位置,却不能用它来更改鼠标的位置。

5.clientY
描述:
返回鼠标在窗口客户区域中的Y坐标。

语法:
event.clientY

注释:
这是个只读属性。这意味着,你只能通过它来得到鼠标的当前位置,却不能用它来更改鼠标的位置。

6.ctrlKey
描述:
检查ctrl键的状态。

语法:
event.ctrlKey

可能的值:
当ctrl键按下时,值为 TRUE ,否则为 FALSE 。只读。

7.fromElement
描述:
检测 onmouseover 和 onmouseout 事件发生时,鼠标所离开的元素。 参考:18.toElement

语法:
event.fromElement

注释:
这是个只读属性。

8.keyCode
描述:
检测键盘事件相对应的内码。
这个属性用于 onkeydown, onkeyup, 和 onkeypress 事件。

语法:
event.keyCode[ = keyCode]

可能的值:
这是个可读写的值,可以是任何一个Unicode键盘内码。如果没有引发键盘事件,则该值为 0 。

9.offsetX
描述:
检查相对于触发事件的对象,鼠标位置的水平坐标

语法:
event.offsetX

10.offsetY
描述:
检查相对于触发事件的对象,鼠标位置的垂直坐标

语法:
event.offsetY

11.propertyName
描述:
设置或返回元素的变化了的属性的名称。

语法:
event.propertyName [ = sProperty ]

可能的值:
sProperty 是一个字符串,指定或返回触发事件的元素在事件中变化了的属性的名称。
这个属性是可读写的。无默认值。

注释:
你可以通过使用 onpropertychange 事件,得到 propertyName 的值。

例子:
下面的例子通过使用 onpropertychange 事件,弹出一个对话框,显示 propertyName 的值。

<HEAD>
<SCRIPT>
function changeProp()
{
btnProp.value = "This is the new VALUE";
}

function changeCSSProp()
{
btnStyleProp.style.backgroundColor = "aqua";
}
</SCRIPT>
</HEAD>
<BODY>
<P>The event object property propertyName is
used here to return which property has been
altered.</P>

<INPUT TYPE=button ID=btnProp onclick="changeProp()"
VALUE="Click to change the VALUE property of this button"
onpropertychange='alert(event.propertyName+" property has changed value")'>
<INPUT TYPE=button ID=btnStyleProp
onclick="changeCSSProp()"
VALUE="Click to change the CSS backgroundColor property of this button"
onpropertychange='alert(event.propertyName+" property has changed value")'>
</BODY>

12.returnValue
描述:
设置或检查从事件中返回的值

语法:
event.returnValue[ = Boolean]

可能的值:
true 事件中的值被返回
false 源对象上事件的默认操作被取消

例子见本文的开头。

13.screenX
描述:
检测鼠标相对于用户屏幕的水平位置

语法:
event.screenX

注释:
这是个只读属性。这意味着,你只能通过它来得到鼠标的当前位置,却不能用它来更改鼠标的位置。

14.screenY
描述:
检测鼠标相对于用户屏幕的垂直位置

语法:
event.screenY

注释:
这是个只读属性。这意味着,你只能通过它来得到鼠标的当前位置,却不能用它来更改鼠标的位置。

15.shiftKey
描述:
检查shift键的状态。

语法:
event.shiftKey

可能的值:
当shift键按下时,值为 TRUE ,否则为 FALSE 。只读。

16.srcElement
描述:
返回触发事件的元素。只读。例子见本文开头。

语法:
event.srcElement

17.srcFilter
描述:
返回触发 onfilterchange 事件的滤镜。只读。

语法:
event.srcFilter

18.toElement
描述:
检测 onmouseover 和 onmouseout 事件发生时,鼠标所进入的元素。 参考:7.fromElement

语法:
event.toElement

注释:
这是个只读属性。

例子:下面的代码演示了当鼠标移到按钮上时,弹出一个对话框,显示“mouse arrived”

<SCRIPT>
function testMouse(oObject) {
if(oObject.contains(event.toElement)) {
alert("mouse arrived");
}
}
</SCRIPT>
:
<BUTTON ID=oButton onmouseover="testMouse(this)">Mouse Over This.</BUTTON>

19.type
描述:
返回事件名。

语法:
event.type

注释:
返回没有“on”作为前缀的事件名,比如,onclick事件返回的type是click
只读。

20. x
描述:
返回鼠标相对于css属性中有position属性的上级元素的x轴坐标。如果没有css属性中有position属性的上级元素,默认以BODY元素作为参考对象。

语法:
event.x

注释:
如果事件触发后,鼠标移出窗口外,则返回的值为 -1
这是个只读属性。这意味着,你只能通过它来得到鼠标的当前位置,却不能用它来更改鼠标的位置。

21. y
描述:
返回鼠标相对于css属性中有position属性的上级元素的y轴坐标。如果没有css属性中有position属性的上级元素,默认以BODY元素作为参考对象。

语法:
event.y

注释:
如果事件触发后,鼠标移出窗口外,则返回的值为 -1
这是个只读属性。这意味着,你只能通过它来得到鼠标的当前位置,却不能用它来更改鼠标的位置

jas

分类:AJAX


B.19 location对象

  它为document对象的一个属性,该文档的完整URL,请不要把它与window.location属性相混淆,后者可用来加载一个新文档,并且window.location属性本身并不是一个对象,同时,window.location可以用脚本修改,而document.location则不能。

  属性

  hash 以散列号(#)开始的一个字符串,用于指定URL内的一个锚点

  host 包括冒号和端口号的URL的主机名部分

  hostname 与host属性相同,除了不包括冒号和端口号之外

  href 完整的URL

  pathname URL的目录路径部分

  port URL的:端口部分

  protocol URL的类型(http:、ftp:、gopher:等等)

  search 以问号(?)开始的URL中的一部分,用于指定搜索信息

  target 用户单击链接(TARGET特性)时,用于显示被引用文档的内容的窗口

  B.20 math对象

  该对象不是其它对象的一个属性,而是一个内置对象,包含了许多数学常量和函数。

  属性

  E 欧拉常量,自然对数的底(约等于2.718)

  LN2 2的自然对数(约等于0.693)

  LN10 10的自然对数(约等于2.302)

  LOG2E 以2为底的e的对数(约等于1.442)

  LOG10E 以10为底的e的对数(约等于o.434)

  PI ∏的值(约等于3.14159)

  SQRT1_2 0.5的平方根(即l除以2的平方根,约等于o.707)

  SQRT2 2的平方根(约等于1.414)

  方法

  abs() 返回某数的绝对值(即该数与o的距离,例如,2与一2的绝对值都是2)

  acos() 返回某数的反余弦值(以弧度为单位)

  asin() 返回某数的反正弦值(以弧度为单位)

  atan() 返回某数的反正切值(以弧度为单位)

  ceil() 返回与某数相等,或大于该数的最小整数(ceil(-22.22)返回-22;ceil22,22)返回23;ceil(22)返回22)

  cos() 返回某数(以弧度为单位)的余弦值

  exp() 返回en

  floor() 与ceil相反(floor(一22.22)返回一23;floor(22.22)返回22; floor(22)返回22)

  10g() 返回某数的自然对数(以e为底)

  max() 返回两数间的较大值

  min() 返回两数问的较小值

  pow() 返回m的n次方(其中,m为底,n为指数)

  random() 返回0和1之间的一个伪随机数(该方法仅在Netscape

  Navigator的UNIX版本中有效)

  round() 返回某数四舍五入之后的整数

  sin() 返回某数(以弧度为单位)的正弦值

  sqrt() 返回某数的平方根

  tan() 返回某数的正切值

  B.2l navigator对象

  该对象不是其它对象的属性,而是一个内置对象它包含了有关加载文档的浏览器的信息。

  属性

  appCodeName 浏览器的代码名(例如,Mozilla)

  appName 浏览器的名字

  appVersion 浏览器的版本号

  userAgent 由客户机送到服务器的用户与代理头标文本

  方法

  javaEnabled JavaScript中当前并没有该方法,但是不久之后将会添加上它将查看浏览器是否为兼容JavaScript的浏览器,如果是,继续查看JavaScript是否处于支持状态。

  B.22 options数组

  该数组是select对象的一个属性,即选择框中的所有选项(<OPTION>)的一个列表。

  属性

  defaultSelected 选项列表中的缺省选项

  index 选项列表中某选项的索引位置

  length 选项列表中的选项数(<OPTIONS>)

  name 选项列表的名字(NAME特性)

  selected 表示选项列表中某选项<OPTION>是否被选中的一个布尔类型值

  selectedIndex 选项列表中已选中的<OPTION>的索引(位置)

  text 选项列表中<OPTION>标记后的文本

  value 选项列表中的VALUE=特性

  B.23 Password 对象

  它是document对象的一个属性,一个<INPUT TYPE=”PASSWORD”>标记。

  属性

  defaultValue password对象的缺省值(VAlUE=特性)

  name 对象的名字(NAME=特性)

  value 该域具有的当前值最初与VALUE=特性(defauttValue)相同,但是,如果脚本修改了该域中的值,则该值将改变

  方法

  focus 把焦点从该域移开

  blur 把焦点移到该域

  select 选择输入区域

  B.24 radio对象

  它是form对象的一个属性,窗体内的一组单选按钮(选项按钮)(<INPUT TYPE=”RADIO”>)。

  属性

  checked 复选框或选项按钮(单选按钮)的状态

  defaultChecked 复选框或选项按钮(单选按钮)的缺省状态

  length 一组单选按钮中的按钮数

  name 对象的名字(NAME=特性)

  value VALUE=特性

  方法

  click 模拟鼠标单击按钮

  事件处理程序

  onclick

  B.25 reset 对象

  它是form对象的一个属性,复位按钮(<INPUT TYPE=”RESET”>)。

  属性

  name 对象的名字(NAME=特性)

  value VALUE=特性

  方法

  click 模拟鼠标单击按钮

  事件处理程序

  onclick

  B.26 select对象

  它是form对象的一个属性,选择框(<SELECT>)。

  属性

  length 选项列表中的选项数(<OPTIONS>)

  name 选项列表的名字(NAME特性)

  options 列表中的选项数

  selectedlndex 选项列表中已选中的<OPTION>的索引(位置)

  text 选项列表中(OPTION)标记之后的文本

  value 选项列表中的VALUE=特性

  方法

  blur 把焦点从选项列表中移走

  focus 把焦点移到选项列表中

  事件处理程序

  Onblur

  onchange

  Onfocus

  B.27 string对象

  它不是另一个对象的属性,而是一个内置对象,即一串字符字符串输入脚本中时必须位于引号内。

  属性

  length 字符串中的字符个数

  方法

  anchor() 用来把字符串转换到HTML锚点标记内(<A NAME=>)

  big() 把字符串中的文本变成大字体(<BIG>)

  blink() 把字符串中的文本变成闪烁字体(<BLINK>)

  bold() 把字符串中的文本变成黑字体(<B>)

  charAt() 寻找字符串中指定位置的一个字符

  fixed() 把字符串中的文本变成固定间距字体(<TT>)

  fontcolor() 改变字符串中文本的颜色(<FONT COLOR=>)

  fontsize() 把字符串中的文本变成指定大小(<FONTSIZE=>)

  indexOf() 用来搜索字符串中的某个特殊字符,并返回该字符的索引位置

  italics() 把字符串中的文本变成斜字体(<I>)

  lastlndexOf() 与indexof相似,但是向后搜索最后一个出现的字符

  link() 用来把字符串转换到HTML链接标记中(<A HREF=>)

  small() 把字符串中的文本变成小字体(<SMALL>)

  strike() 把字符串中的文本变成划掉字体(<STRIKE>)

  sub() 把字符串中的文本变成下标(subscript)字体((SUB>)

  substring() 返回字符串里指定位置间的一部分字符串

  sup() 把字符串中的文本变成上标(superscript)字体(<SUP>)

  toLowerCase() 把字符串中的文本变成小写

  toUpperCase() 把字符串中的文本变成大写

  B.28 submit对象

  它是form对象的一个属性,窗体中的一个提交按钮(<INPUT TYPE=”SUBMIT”>)。

  属性

  name 对象的名字(NAME=特性)

  value VALUE=特性

  方法

  click 模拟鼠标单击按钮

  事件处理程序

  Onclick

  B.29 text对象

  它是form对象的一个属性,宙体中的一个文本域(<INPUT TYPE=”TEXT”>)。

  属性

  defaultValue text对象的缺省值(VALUE=特性)

  name 该对象的名字(NAME=特性)

  Value 该域具有的当前值,最初与VALUE=特性(defaultValue)相同但是,如果脚本修改了该域中的值,则该值将改变

  方法

  blur 把焦点从文本框移开

  focus 把焦点移到文本框

  select 选择输入区域

  事件处理程序

  Onblur

  Onchange

  Onfeus

  Onselect

  B.30 textarea对象

  它是form对象的一个属性,宙体中的一个文本区域(<TEXTAREA>)。

  属性

  defaultValue textarea对象的缺省值(VALUE=特性)

  name 该对象的名字(NAME=特性)

  value 该域具有的当前值,最初与VALUE=特性(defaultValue)相同,但是,如果脚本修改了该域中的值,则该值将改变了。

  方法

  blur 把焦点从文本区移开

  focus 把焦点移到文本区

  select 选择输入区域事件处理程序

  Onblur

  Onchange

  Onfocus

  Onselect

  B.31 window对象

  它是一个顶层对象,而不是另一个对象的属性即浏览器的窗口。

  属性

  defaultStatus 缺省的状态条消息

  document 当前显示的文档(该属性本身也是一个对象)

  frame 窗口里的一个框架((FRAME>)(该属性本身也是一个对象)

  frames array 列举窗口的框架对象的数组,按照这些对象在文档中出现的顺序列出(该属性本身也是一个对象)

  history 窗口的历史列表(该属性本身也是一个对象)

  length 窗口内的框架数

  location 窗口所显示文档的完整(绝对)URL(该属性本身也是一个对象)不要把它与如document.location混淆,后者是当前显示文档的URL。用户可以改变window.location(用另一个文档取代当前文档),但却不能改变document.location(因为这是当前显示文档的位置)

  name 窗口打开时,赋予该窗口的名字

  opener 代表使用window.open打开当前窗口的脚本所在的窗口(这是Netscape Navigator 3.0beta 3所引入的一个新属性)

  parent 包含当前框架的窗口的同义词。frame和window对象的一个属性

  self 当前窗口或框架的同义词

  status 状态条中的消息

  top 包含当前框架的最顶层浏览器窗口的同义词

  window 当前窗口或框架的同义词,与self相同

  方法

  alert() 打开一个Alert消息框

  clearTimeout() 用来终止setTimeout方法的工作

  close() 关闭窗口

  confirm() 打开一个Confirm消息框,用户可以选择OK或Cancel,如果用户单击OK,该方法返回true,单击Cancel返回false

  blur() 把焦点从指定窗口移开(这是Netscape Navigator 3.0 beta 3引入的新方法)

  focus() 把指定的窗口带到前台(另一个新方法)

  open() 打开一个新窗口

  prompt() 打开一个Prompt对话框,用户可向该框键入文本,并把键入的文本返回到脚本

  setTimeout() 等待一段指定的毫秒数时间,然后运行指令事件处理程序

  OnloadOnunload
用JS显示文字的例子:

<html>
<body>

<script type="text/javascript">
document.write("Hello World!")
</script>

</body>
</html>

用HTML标签来格式化文本的例子:

<html>
<body>

<script type="text/javascript">
document.write("<h1>Hello World!</h1>")
</script>

</body>
</html>

书写JS位置的例子:

打开页面弹出窗口的例子

<html>
<head>
<script type="text/javascript">
function message()
{
alert("网页教学网欢迎你的光临")
}
</script>
</head>

<body "message()">

</body>
</html>


在BODY区内输出显示文本的例子:

<html>
<head>
</head>

<body>

<script type="text/javascript">
document.write("欢迎光临网页教学网http://www.webjx.com")
</script>

</body>
</html>


调用其它的一个JS文件的例子:

<html>
<head>
</head>
<body>

<script src="xxx.js">
</script>

<p>
The actual script is in an external script file called "xxx.js".
</p>

</body>
</html>


变量的使用


变量使用的例子:


<html>
<body>

<script type="text/javascript">
var name = "Hege"
document.write(name)
document.write("<h1>"+name+"</h1>")
</script>

<p>This example declares a variable, assigns a value to it, and then displays the variable.</p>

<p>Then the variable is displayed one more time, only this time as a heading.</p>

</body>
</html>


函数的例子

函数使用的一个例子:

<html>
<head>

<script type="text/javascript">
function myfunction()
{
alert("HELLO")
}
</script>

</head>
<body>

<form>
<input type="button"
onclick="myfunction()"
value="Call function">
</form>

<p>By pressing the button, a function will be called. The function will alert a message.</p>

</body>
</html>

带一个参数的函数的例子:

<html>
<head>

<script type="text/javascript">
function myfunction(txt)
{
alert(txt)
}
</script>

</head>
<body>

<form>
<input type="button"
onclick="myfunction('Hello')"
value="Call function">
</form>

<p>By pressing the button, a function with an argument will be called. The function will alert
this argument.</p>

</body>
</html>

不同的两个参数调用函数的例子:

<html>
<head>
<script type="text/javascript">
function myfunction(txt)
{
alert(txt)
}
</script>
</head>

<body>
<form>
<input type="button"
onclick="myfunction('Good Morning!')"
value="In the Morning">

<input type="button"
onclick="myfunction('Good Evening!')"
value="In the Evening">
</form>

<p>
When you click on one of the buttons, a function will be called. The function will alert
the argument that is passed to it.
</p>

</body>
</html>

利用函数返回值的例子:

<html>
<head>

<script type="text/javascript">
function myFunction()
{
return ("Hello, have a nice day!")
}
</script>

</head>
<body>

<script type="text/javascript">
document.write(myFunction())
</script>

<p>The script in the body section calls a function.</p>

<p>The function returns a text.</p>

</body>
</html>


带参数的函数返回值的例子:


<html>
<head>

<script type="text/javascript">
function total(numberA,numberB)
{
return numberA + numberB
}
</script>

</head>
<body>

<script type="text/javascript">
document.write(total(2,3))
</script>

<p>The script in the body section calls a function with two arguments, 2 and 3.</p>

<p>The function returns the sum of these two arguments.</p>

</body>
</html>


条件语句的例子


简单条件语句的例子:

<html>
<body>

<script type="text/javascript">
var d = new Date()
var time = d.getHours()

if (time < 10)
{
document.write("<b>Good morning</b>")
}
</script>

<p>
This example demonstrates the If statement.
</p>

<p>
If the time on your browser is less than 10,
you will get a "Good morning" greeting.
</p>

</body>
</html>

if ... else 的条件语句的例子:


<html>
<body>

<script type="text/javascript">
var d = new Date()
var time = d.getHours()

if (time < 10)
{
document.write("<b>Good morning</b>")
}
else
{
document.write("<b>Good day</b>")
}
</script>

<p>
This example demonstrates the If...Else statement.
</p>

<p>
If the time on your browser is less than 10,
you will get a "Good morning" greeting.
Otherwise you will get a "Good day" greeting.
</p>

</body>
</html>


用随机数产生连接的例子:

<html>
<body>

<script type="text/javascript">
var r=Math.random()
if (r>0.5)
{
document.write("<a href='http://www.w3schools.com'>Learn Web Development!</a>")
}
else
{
document.write("<a href='http://www.refsnesdata.no'>Visit Refsnes Data!</a>")
}
</script>

</body>
</html>

多条件的语句实现的例子:

<html>
<body>
<script type="text/javascript">
var d = new Date()
theDay=d.getDay()
switch (theDay)
{
 case 5:
  document.write("Finally Friday")
 break
 case 6:
  document.write("Super Saturday")
 break
 case 0:
  document.write("Sleepy Sunday")
 break
 default:
  document.write("I'm really looking forward to this weekend!")
}
</script>

<p>This example demonstrates the switch statement.</p>

<p>You will receive a different greeting based on what day it is.</p>

<p>Note that Sunday=0, Monday=1, Tuesday=2, etc.</p>

</body>
</html>


循环的例子:

for循环的一个例子:

<html>
<body>

<script type="text/javascript">
for (i = 0; i <= 5; i++)
{
document.write("The number is " + i)
document.write("<br>")
}
</script>

<p>Explanation:</p>

<p>The for loop sets <b>i</b>  equal to 0.</p>

<p>As long as <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p>

<p><b>i</b> will increase by 1 each time the loop runs.</p>

</body>
</html>

复杂循环的一个例子:

<html>
<body>

<script type="text/javascript">
for (i = 1; i <= 6; i++)
{
document.write("<h" + i + ">This is header " + i)
document.write("</h" + i + ">")
}
</script>

</body>
</html>

按条件循环while的例子:

<html>
<body>

<script type="text/javascript">
i = 0
while (i <= 5)
{
document.write("The number is " + i)
document.write("<br>")
i++
}
</script>

<p>Explanation:</p>

<p><b>i</b>  equal to 0.</p>

<p>While <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p>

<p><b>i</b> will increase by 1 each time the loop runs.</p>

</body>
</html>

do...while循环的例子:

<html>
<body>

<script type="text/javascript">
i = 0
do
{
document.write("The number is " + i)
document.write("<br>")
i++
}
while (i <= 5)
</script>

<p>Explanation:</p>

<p><b>i</b>  equal to 0.</p>

<p>The loop will run</p>

<p><b>i</b> will increase by 1 each time the loop runs.</p>

<p>While <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p>


</body>
</html>


字符串对象的例子:

 

检测字符串长度的例子:

<html>
<body>

<script type="text/javascript">
var str="W3Schools is great!"
document.write("<p>" + str + "</p>")
document.write(str.length)
</script>

</body>
</html>


检测子字符串位置的例子:

<html>
<body>

<script type="text/javascript">
var str="W3Schools is great!"
var pos=str.indexOf("School")
if (pos>=0)
{
document.write("School found at position: ")
document.write(pos + "<br />")
}
else
{
document.write("School not found!")
}
</script>

<p>This example tests if a string contains a specified word. If the word is found it returns the position of the first character of the word in the original string. Note: The first position in the string is 0!</p>

</body>
</html>

检测子字符串是否存在的例子:

<html>
<body>

<script type="text/javascript">
var str = "W3Schools is great!"
document.write(str.match("great"))
</script>

<p>This example tests if a string contains a specified word. If the word is found it returns the word.</p>

</body>
</html>


取子字符串的例子:

<html>
<body>

<script type="text/javascript">
var str="W3Schools is great!"
document.write(str.substr(2,6))
document.write("<br /><br />")
document.write(str.substring(2,6))
</script>

<p>
The substr() method returns a specified part of a string. If you specify (2,6) the returned string will be from the second character (start at 0) and 6 long.
</p>

<p>
The substring() method also returns a specified part of a string. If you specify (2,6) it returns all characters from the second character (start at 0) and up to, but not including, the sixth character.
</p>

</body>
</html>

转换字符串的大小写

<html>
<body>

<script type="text/javascript">
var str=("Hello JavaScripters!")
document.write(str.toLowerCase())
document.write("<br>")
document.write(str.toUpperCase())
</script>

</body>
</html>


数组对象的实例


数组简单应用的例子:


<html>
<body>

<script type="text/javascript">
var famname = new Array(6)
famname[0] = "Jan Egil"
famname[1] = "Tove"
famname[2] = "Hege"
famname[3] = "Stale"
famname[4] = "Kai Jim"
famname[5] = "Borge"

for (i=0; i<6; i++)
{
document.write(famname[i] + "<br>")
}
</script>

</body>
</html>


另一种使用数组的方法:

<html>
<body>

<script type="text/javascript">
var famname = new Array("Jan Egil","Tove","Hege","Stale","Kai Jim","Borge")

for (i=0; i<famname.length; i++)
{
document.write(famname[i] + "<br>")
}
</script>

</body>
</html>


使用数组的一些属性和方法:

<html>
<body>

<script type="text/javascript">
var famname = new Array(3)
famname[0] = "Jani"
famname[1] = "Tove"
famname[2] = "Hege"

document.write(famname.length + "<br>")
document.write(famname.join(".") + "<br>")
document.write(famname.reverse() + "<br>")
document.write(famname.push("Ola","Jon") + "<br>")
document.write(famname.pop() + "<br>")
document.write(famname.shift() + "<br>")
</script>

</body>
</html>


数组的两个方法concat和slice

<html>
<body>

<script type="text/javascript">
var famname = new Array(3)
famname[0] = "Jani"
famname[1] = "Tove"
famname[2] = "Hege"

var famname2 = new Array(3)
famname2[0] = "John"
famname2[1] = "Andy"
famname2[2] = "Wendy"

var famname3 = new Array("Stale","Borge")

document.write(famname.join() + "<br>")
document.write(famname.concat(famname2) + "<br>")
document.write(famname.concat(famname2,famname3) + "<br>")
document.write(famname.slice(1) + "<br>")
</script>

</body>
</html>

日期相关例子:


显示今天的日期:

<html>
<body>

<script type="text/javascript">
var d = new Date()
document.write(d.getDate())
document.write(".")
document.write(d.getMonth() + 1)
document.write(".")
document.write(d.getFullYear())
</script>

</body>
</html>


显示当前的时间:

<html>
<body>

<script type="text/javascript">
var d = new Date()
document.write(d.getHours())
document.write(".")
document.write(d.getMinutes())
document.write(".")
document.write(d.getSeconds())
</script>

</body>
</html>

设置日期:

<html>
<body>

<script type="text/javascript">
var d = new Date()
d.setFullYear("1990")
document.write(d)
</script>

</body>
</html>

UTC时间:

<html>
<body>

<script type="text/javascript">
var d = new Date()
document.write(d.getUTCHours())
document.write(".")
document.write(d.getUTCMinutes())
document.write(".")
document.write(d.getUTCSeconds())
</script>

</body>
</html>

显示当前的星期:

<html>
<body>
<script type="text/javascript">
var d=new Date()
var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
document.write("Today is " + weekday[d.getDay()])
</script>
</body>
</html>

显示当前的日期和星期:

<html>
<body>
<script type="text/javascript">
var d=new Date()
var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
document.write(weekday[d.getDay()] + " ")
document.write(d.getDate() + ". ")
document.write(monthname[d.getMonth()] + " ")
document.write(d.getFullYear())
</script>
</body>
</html>

一个走动的时间:

<html>
<head>
<script type="text/javascript">
var timer = null

function stop()
{
clearTimeout(timer)
}

function start()
{
var time = new Date()
var hours = time.getHours()
var minutes = time.getMinutes()
minutes=((minutes < 10) ? "0" : "") + minutes
var seconds = time.getSeconds()
seconds=((seconds < 10) ? "0" : "") + seconds
var clock = hours + ":" + minutes + ":" + seconds
document.forms[0].display.value = clock
timer = setTimeout("start()",1000)
}
</script>
</head>
<body "start()" onunload="stop()">
<form>
<input type="text" name="display" size="20">
</form>
</body>
</html>

数学对象的例子:


<html>
<body>

<script type="text/javascript">
document.write(Math.round(7.25))
</script>

</body>
</html>


产生0-1之间的随机数的例子

<html>
<body>

<script type="text/javascript">
document.write(Math.random())
</script>

</body>
</html>

产生0-10的随机数的例子

<html>
<body>

<script type="text/javascript">
no=Math.random()*10
document.write(Math.round(no))
</script>

</body>
</html>


求最大数的例子:

<html>
<body>

<script type="text/javascript">
document.write(Math.max(2,4))
</script>

</body>
</html>

求最小数的例子:

<html>
<body>

<script type="text/javascript">
document.write(Math.min(2,4))
</script>

</body>
</html>

Convert Celsius to Fahrenheit


<html>
<head>
<script type="text/javascript">
function convert(degree)
{
if (degree=="C")
 {
 F=document.myform.celsius.value * 9 / 5 + 32
 document.myform.fahrenheit.value=Math.round(F)
 }
else
 {
 C=(document.myform.fahrenheit.value -32) * 5 / 9
 document.myform.celsius.value=Math.round(C)
 }
}
</script>
</head>
<body>

<b>Insert a number in either input field, and the number will be converted into
either Celsius or Fahrenheit.</b>
<br />
<form name="myform">
<input name="celsius" onkeyup="convert('C')"> degrees Celsius<br />
equals<br />
<input name="fahrenheit" onkeyup="convert('F')"> degrees Fahrenheit
</form>
<br />
Note that the <b>Math.round</b> method is used,
so that the result will be returned as a whole number.

</body>
</html>


转变字符为数字的例子

<html>
<head>

<script type="text/javascript">
function toUnicode()
{
var str=document.myForm.myInput.value
if (str!="")
 {
 unicode=str.charCodeAt(0)
 }
document.myForm.unicode.value=unicode
}
</script>
</head>
<body>

<form name="myForm">
Write a character:<br />
<input size="1" name="myInput" maxlength="1" onkeyup="toUnicode()">
<hr />
The character's Unicode:<br />
<input size="3" name="unicode">
</form>

</html>


超级连接对象

用按钮来改变连接位置的例子:

<html>

<head>
<script type="text/javascript">
function myHref()
{
document.getElementById('myAnchor').innerText="Visit W3Schools"
document.getElementById('myAnchor').href="http://www.w3schools.com"
}
</script>
</head>

<body>
<a id="myAnchor" href="http://www.microsoft.com">Visit Microsoft</a>
<form>
<input type="button" onclick="myHref()" value="Change URL and text">
</form>
</body>

</html>


改变连接的打开方式的例子:

<html>

<head>
<script type="text/javascript">
function myTarget()
{
document.getElementById('myAnchor').target="_blank"
}
</script>
</head>

<body>
<a id="myAnchor" href="http://www.w3schools.com">Visit W3Schools</a>
<form>
<input type="button" onclick="myTarget()" value="Make the link open in a new window!">
</form>
<p>Try the link before and after you have pressed the button!</p>
</body>

</html>


使连接获得焦点和失去焦点

<html>

<head>
<style type="text/css">
a:active {color:blue}
</style>
<script type="text/javascript">
function getfocus()
{
document.getElementById('w3s').focus()
}

function losefocus()
{
document.getElementById('w3s').blur()
}
</script>
</head>

<body>
<a id="w3s" href="http://www.w3schools.com">Visit W3Schools.com</a>
<form>
<input type="button" onclick="getfocus()" value="Get Focus">
<input type="button" onclick="losefocus()" value="Lose Focus">
</form>
</body>

</html>

连接打开的方式


<html>
<body>

<script type="text/javascript">
function linkToAnchor(num)
{
var win2=open("tryjs_anchor2.htm","secondLinkWindow","scrollbars=yes,width=250,height=200")
win2.location.hash=num
}
</script>

<h3>Links and Anchors</h3>
<p>Click on a button to display that anchor in window 2!</p>
<form>
<input type="button" value="0" onClick="linkToAnchor(this.value)">
<input type="button" value="1" onClick="linkToAnchor(this.value)">
<input type="button" value="2" onClick="linkToAnchor(this.value)">
<input type="button" value="3" onClick="linkToAnchor(this.value)">
</form>

</body>
</html>


按钮对象


创建一个按钮

<html>
<head>
<script type="text/javascript">
function show_alert()
{
alert("Hello World!")
document.all("myButton").focus()
}
</script>
</head>

<body>
<form>
<input type="button" value="Click me!" name="myButton" onClick="show_alert()" />
</form>
</body>

</html>


显示按钮的名称

<html>

<body>
<form name="myForm">
The form's name is: <input type="text" name="text1" size="20">
<br /><br />
<input type="button" value="Show the form's name" onClick="this.form.text1.value=this.form.name">
</form>
</body>

</html>


显示表单中各个项的名称

<html>
<head>
<script type="text/javascript">
function showFormElements(theForm)
{
str="Form Elements: "
for (i=0; i<theForm.length; i++)
str+=" n " + theForm.elements[i].name
alert(str)
}
</script>
</head>

<body>
<form>
First name: <input type="text" name="fname" size="20">
<br />
Last name: <input type="text" name="lname" size="20">
<br /><br />
<input type="button" name="button1"
value="Display name of form elements"
onClick="showFormElements(this.form)">
</form>
</body>

</html>


副选框的选择和取消

<html>

<head>
<script type="text/javascript">
function check()
{
var x=document.forms.myForm
x[0].checked=true
}

function uncheck()
{
var x=document.forms.myForm
x[0].checked=false
}
</script>
</head>

<body>

<form name="myForm">
<input type="checkbox" value="on">
<input type="button" onclick="check()" value="Check Checkbox">
<input type="button" onclick="uncheck()" value="Uncheck Checkbox">
</form>

</body>
</html>


表单中的副选框的选择与取消

<html>

<head>
<script type="text/javascript">
function check()
{
coffee=document.forms[0].coffee
answer=document.forms[0].answer
txt=""
for (i=0;i<coffee.length;++ i)
{
if (coffee[i].checked)
{
txt=txt + coffee[i].value + " "
}
}
answer.value="You ordered a coffee with " + txt
}
</script>
</head>

<body>
<form>
How would you like your coffee?<br /><br />
<input type="checkbox" name="coffee" value="cream">With cream<br />
<input type="checkbox" name="coffee" value="sugar">With sugar<br />
<br />
<input type="button" name="test" onclick="check()" value="Send order">
<br /><br />
<input type="text" name="answer" size="50">
</form>
</body>

</html>


副选框实现的功能(转换为大写)

<html>
<body>

<script type="text/javascript">
function convertField(field)
{
if (document.form1.convertUpper.checked)
 {
 field.value=field.value.toUpperCase()
 }
}

function convertAllFields()
{
document.form1.fname.value=document.form1.fname.value.toUpperCase()
document.form1.lname.value=document.form1.lname.value.toUpperCase()
}
</script>

<form name="form1">
First name:
<input type="text" name="fname" onChange="convertField(this)" size="20" />
<br />
Last name:
<input type="text" name="lname" onChange="convertField(this)" size="20" />
<br />
Convert fields to upper case
<input type="checkBox" name="convertUpper" onClick="if (this.checked) {convertAllFields()}" value="ON">
</form>

</body>
</html>

文档对象

显示连接的数量

<html>
<body>

<a name="A">First anchor</a><br />
<a name="B">Second anchor</a><br />
<a name="C">Third anchor</a><br />
<br />

Number of anchors in this document:
<script type="text/javascript">
document.write(document.anchors.length)
</script>

</body>
</html>

显示当前所在服务器的地址

<html>
<body>

The domain name for this site is:
<script type="text/javascript">
document.write(document.domain)
</script>

</body>
</html>


显示当前页面的地址:

<html>
<body>

<p>The referrer of a document is the URL of the document that linked to a document.</p>

The referrer of this document is:
<script type="text/javascript">
document.write(document.referrer)
</script>

<p>In this case it is a frame page that is linking to this document. IE returns the URL of the frame page and Netscape returns the URL of the document linking to this document.</p>

</body>
</html>


显示当前文档的标题

<html>
<head>
<title>MY TITLE</title>
</head>

<body>
The title of the document is:
<script type="text/javascript">
document.write(document.title)
</script>
</body>

</html>

用按钮来显示当前页面的地址

<html>
<head>
<script type="text/javascript">
function showURL()
{
alert(document.URL)
}
</script>
</head>

<body>
<form>
<input type="button" onclick="showURL()" value="Show URL">
</form>
</body>

</html>


通过单击可以知道当前的标签

<html>

<head>
<script type="text/javascript">
function getElement()
{
var x=document.getElementById("myHeader")
alert("I am a " + x.tagName + " element")
}
</script>
</head>

<body>
<h1 id="myHeader" onclick="getElement()">Click to see what element I am!</h1>
</body>

</html>


显示表单中元素的个数

<html>

<head>
<script type="text/javascript">
function getElements()
{
var x=document.getElementsByName("myInput")
alert(x.length + " elements!")
}
</script>
</head>
<body>

<form >
<input name="myInput" type="text" size="20"><br />
<input name="myInput" type="text" size="20"><br />
<input name="myInput" type="text" size="20"><br />
<br />
<input name="mybutton" type="button" onclick="getElements()" value="Show how many elements named 'myInput'">
</form>
</body>

</html>


打开一个新的文档,显示几个文字

<html>

<head>
<script type="text/javascript">
function docOpen()
{
document.open()
document.write("<h3>Hello World!</h3>")
}
</script>
</head>

<body>
<form>
<input type="button" onclick="docOpen()" value="Open a new document">
</form>
</body>

</html>


打开一个新的文档,并显示新的文档

<html>
<head>
<script>
function replace()
{
var newDoc=document.open("text/html","replace")
var txt="<html><body>FUN!!!!</body></html>"
newDoc.write(txt)
newDoc.close()
}
</script>
</head>

<body>
<h1>Learning how to access the DOM is....</h1><br />
<Input type ="button" value = "Finish Sentence" onclick="replace()">
</body>

</html>


计算表单的个数

<html>

<body>
<form name="Form1">
Name: <input type="text" size="20">
</form>
<form name="Form2">
Age: <input type="text" size="3">
</form>

<script type="text/javascript">
txt="This document contains: " + document.forms.length + " forms."
document.write(txt)
</script>
</body>

</html>


计算一个页面中图形的个数

<html>

<body>
<img border="0" src="hackanm.gif" width="48" height="48">
<br />
<img border="0" src="compman.gif" width="107" height="98">

<p>
<script type="text/javascript">
document.write("This document contains: " + document.images.length + " images.")
</script>
</p>
</body>

</html>

显示表单的名字

<html>

<body>
<form name="Form1">
Name: <input type="text" size="20">
</form>
<form name="Form2">
Age: <input type="text" size="3">
</form>

<p><b>You can use the form's number:</b></p>
<script type="text/javascript">
document.write("<p>The first form's name is: ")
document.write(document.forms[0].name + "</p>")
document.write("<p>The second form's name is: ")
document.write(document.forms[1].name + "</p>")
</script>

<p><b>Or, the form's name (will not work in Netscape):</b></p>
<script type="text/javascript">
document.write("<p>The first form's name is: ")
document.write(document.forms("Form1").name + "</p>")
document.write("<p>The second form's name is: ")
document.write(document.forms("Form2").name + "</p>")
</script>
</body>

</html>


事件对象

单击弹出窗口

<html>
<head>
<script type="text/javascript">
function whichButton()
{
if (event.button==1)
{
alert("You clicked the left mouse button!")
}
else
{
alert("You clicked the right mouse button!")
}
}
</script>
</head>

<body onmousedown="whichButton()">
<p>Click in the document. An alert box will alert which mouse button you clicked.</p>
</body>

</html>


单击弹出窗口显示鼠标的位置

<html>
<head>
<script type="text/javascript">
function show_coords()
{
x=event.clientX
y=event.clientY
alert("X coords: " + x + ", Y coords: " + y)
}
</script>
</head>

<body onmousedown="show_coords()">
<p>Click in the document. An alert box will alert the x and y coordinates of the cursor.</p>
</body>

</html>


按一个键则显示该键的ASCII码

<html>
<head>
<script type="text/javascript">
function whichButton()
{
alert(event.keyCode)
}

</script>
</head>

<body onkeyup="whichButton()">
<p><b>Note:</b> Make sure the right frame has focus when trying this example!</p>
<p>Press a key on your keyboard. An alert box will alert the unicode of the key pressed.</p>
</body>

</html>


单击任何地方显示鼠标在页面的坐标

<html>
<head>

<script type="text/javascript">
function coordinates()
{
x=event.screenX
y=event.screenY
alert("X=" + x + " Y=" + y)
}

</script>
</head>
<body onmousedown="coordinates()">

<p>
Click somewhere in the document. An alert box will alert the x and y coordinates of the cursor, relative to the screen.
</p>

</body>
</html>


单击之后显示文档的鼠标坐标

<html>
<head>

<script type="text/javascript">
function coordinates()
{
x=event.x
y=event.y
alert("X=" + x + " Y=" + y)
}

</script>
</head>
<body onmousedown="coordinates()">

<p>
Click somewhere in the document. An alert box will alert the x and y coordinates of the cursor.
</p>

</body>
</html>

 

显示SHIFT是否被按下

<html>
<head>

<script type="text/javascript">
function isKeyPressed()
{
if (event.shiftKey==1)
{
alert("The shift key was pressed!")
}
else
{
alert("The shift key was NOT pressed!")
}
}

</script>
</head>
<body onmousedown="isKeyPressed()">

<p>
Click somewhere in the document. An alert box will tell you if you pressed the shift key or not.
</p>

</body>
</html>


单击显示我们页中的标签

<html>
<head>
<script type="text/javascript">
function whichElement()
{
var tname
tname=event.srcElement.tagName
alert("You clicked on a " + tname + " element.")
}
</script>
</head>

<body onmousedown="whichElement()">
<p>Click somewhere in the document. An alert box will alert the tag name of the element you clicked on.</p>

<h3>This is a header</h3>
<p>This is a paragraph</p>
<img border="0" src="ball16.gif" width="29" height="28" alt="Ball">
</body>

</html>


显示事件发生的类型

<html>
<head>

<script type="text/javascript">
function whichType()
{
alert(event.type)
}
</script>
</head>

<body onmousedown="whichType()">

<p>
Click on the document. An alert box will alert which type of event occurred.
</p>

</body>
</html>


表单对象

用表单显示地址:

<html>

<head>
<script type="text/javascript">
function getAction()
{
var x=document.forms.myForm
alert(x.action)
}

function changeAction()
{
var x=document.forms.myForm
x.action="default.asp"
alert(x.action)
}
</script>
</head>

<body>
<form name="myForm" action="js_examples.asp">
<input type="button" onclick="getAction()" value="View value of action attribute">
<br /><br />
<input type="button" onclick="changeAction()" value="Change value of action attribute">
</form>
</body>

</html>


显示表单所使用的方法

<html>

<head>
<script type="text/javascript">
function formMethod()
{
var x=document.forms.myForm
alert(x.method)
}
</script>
</head>

<body>
<form name="myForm" method="post">
Name: <input type="text" size="20"><br /><br />
<input type="button" onclick="formMethod()" value="Show method">
</form>
</body>

</html>

重置表单

<html>
<head>

<script type="text/javascript">
function formReset()
{
var x=document.forms.myForm
x.reset()
}
</script>

</head>
<body>

<form name="myForm">
<p>Enter some text in the text fields and then press the "Reset form" button</p>
<input type="text" size="20"><br />
<input type="text" size="20"><br />
<br />
<input type="button" onclick="formReset()" value="Reset form">
</form>

</body>
</html>

提交表单

<html>

<head>
<script type="text/javascript">
function formSubmit()
{
document.forms.myForm.submit()
}
</script>
</head>

<body>
<form name="myForm" action="js_form_action.asp" method="get">
Firstname: <input type="text" name="firstname" size="20"><br />
Lastname: <input type="text" name="lastname" size="20"><br /><br />
<input type="button" onclick="formSubmit()" value="Submit">
</form>
</body>

</html>


对email的验证

<html>

<head>
<script type="text/javascript">
function validate()
{
x=document.myForm
at=x.email.value.indexOf("@")
if (at == -1)
 {
 alert("Not a valid e-mail")
 return false
 }
}
</script>
</head>

<body>
<form name="myForm" action="tryjs_submitpage.htm" onsubmit="return validate()">
Enter your E-mail:
<input type="text" name="email" size="20">
<input type="submit" value="Submit">
</form>
<p><b>Note:</b> This example ONLY tests if the e-mail address contains an "@" character. A "real-life" code
would have to test for punctuations, spaces and other things as well.</p>
</body>

</html>


输入指定的数才能提交表单

<html>

<head>
<script type="text/javascript">
function validate()
{
x=document.myForm
txt=x.myInput.value
if (txt>=1 && txt<=5)
 {
 return true
 }
else
 {
 alert("Must be between 1 and 5")
 return false
 }
}
</script>
</head>

<body>
<form name="myForm" action="tryjs_submitpage.htm" onsubmit="return validate()">
Enter a value from 1 to 5: <input type="text" name="myInput" size="20">
<input type="submit" value="Submit">
</form>
</body>

</html>


输入特定长的字符才能提交表单

<html>

<head>
<script type="text/javascript">
function validate()
{
x=document.myForm
input=x.myInput.value
if (input.length>5)
 {
 alert("The field cannot contain more than 5 characters!")
 return false
 }
else
 {
 return true
 }
}
</script>
</head>

<body>
<form name="myForm" action="tryjs_submitpage.htm" onsubmit="return validate()">
Enter some text (you will get a message if you add more than 5 characters):
<input type="text" name="myInput" size="20">
<input type="submit" value="Submit">
</form>
</body>

</html>


对表单的检测

<html>

<head>
<script type="text/javascript">
function validate()
{
x=document.myForm
at=x.email.value.indexOf("@")
code=x.code.value
firstname=x.fname.value
submitOK="True"

if (at==-1)
 {
 alert("Not a valid e-mail!")
 submitOK="False"
 }
if (code<1 || code>5)
 {
 alert("The value must be between 1 and 5")
 submitOK="False"
 }
if (firstname.length>10)
 {
 alert("Your name must be less than 10 characters")
 submitOK="False"
 }
if (submitOK=="False")
 {
 return false
 }
}
</script>
</head>

<body>
<form name="myForm" action="tryjs_submitpage.htm" onsubmit="return validate()">
Enter your e-mail: <input type="text" name="email" size="20"><br />
Enter a value from 1 to 5: <input type="text" name="code" size="20"><br />
Enter your name, max 10 chararcters: <input type="text" name="fname" size="20"><br />
<input type="submit" value="Submit">
</form>
</body>

</html>


设置表单中的一项获得焦点

<html>

<head>
<script type="text/javascript">
function setfocus()
{
document.forms[0].field.focus()
}
</script>
</head>

<body>
<form>
<input type="text" name="field" size="30">
<input type="button" value="Set focus" onclick="setfocus()">
</form>
</body>

</html>


选择文本框中的文本

<html>

<head>
<script type="text/javascript">
function setfocus()
{
document.forms[0].txt.select()
document.forms[0].txt.focus()
}
</script>
</head>

<body>
<form>
<input type="text" name="txt" size="30" value="Hello World!">
<input type="button" value="Select text" onclick="setfocus()">
</form>
</body>

</html>


下拉列表框的取值

<html>
<head>
<script type="text/javascript">
function put()
{
txt=document.forms[0].myList.options[document.forms[0].myList.selectedIndex].text
document.forms[0].favorite.value=txt
}
</script>
</head>

<body>
<form>
Select your favorite browser:
<select name="myList" onchange="put()">
 <option>Internet Explorer</option>
 <option>Netscape</option>
 <option>Opera</option>
</select>
<br /><br />
Your favorite browser is: <input type="text" name="favorite" size="20">
</form>
</body>

</html>


单选按钮的取值

<html>

<head>
<script type="text/javascript">
function check(browser)
{
document.forms[0].answer.value=browser
}
</script>

</head>

<body>
<form>
Select which browser is your favorite:<br /><br />
<input type="radio" name="browser" onclick="check(this.value)" value="Internet Explorer">Internet Explorer<br />
<input type="radio" name="browser" onclick="check(this.value)" value="Netscape">Netscape<br />
<input type="radio" name="browser" onclick="check(this.value)" value="Opera">Opera<br />
<br />
<input type="text" name="answer" size="20">
</form>
</body>

</html>


下拉列表的值的显示

<html>
<head>
<script type="text/javascript">
function put()
{
option=document.forms[0].dropdown.options[document.forms[0].dropdown.selectedIndex].text
txt=document.forms[0].number.value
txt=txt + option
document.forms[0].number.value=txt
}
</script>
</head>

<body>
<form>
Select numbers:<br />
<select name="dropdown">
 <option>0</option>
 <option>1</option>
 <option>2</option>
 <option>3</option>
 <option>4</option>
 <option>5</option>
 <option>6</option>
 <option>7</option>
 <option>8</option>
 <option>9</option>
</select>
<input type="button" onclick="put()" value="-->">
<input type="text" name="number" size="20">
</form>
</body>

</html>


下拉列表的连接

<html>
<head>
<script type="text/javascript">
function go(form)
{
location=form.selectmenu.value
}
</script>
</head>

<body>
<form>
<select name="selectmenu" onchange="go(this.form)">
  <option>--Select page--</option>
  <option value="http://www.microsoft.com">Microsoft</option>
  <option value="http://www.altavista.com">AltaVista</option>
  <option value="http://www.w3schools.com">W3Schools</option>
</select>
</form>
</body>

</html>


光标自动跳到下一个文本区

<html>
<head>
<script type="text/javascript">
function toUnicode(elmnt,content)
{
if (content.length==elmnt.maxLength)
 {
 next=elmnt.tabIndex
 if (next<document.forms[0].elements.length)
  {
  document.forms[0].elements[next].focus()
  }
 }
}
</script>
</head>

<body>
<p>This script automatically jumps to the next input field when the current field's maxlength has been reached.</p>
<form>
<input size="3" tabindex="1" maxlength="3" onkeyup="toUnicode(this,this.value)">
<input size="3" tabindex="2" maxlength="3" onkeyup="toUnicode(this,this.value)">
<input size="3" tabindex="3" maxlength="3" onkeyup="toUnicode(this,this.value)">
</form>
</body>

</html>


Frame, Frameset 和 IFrame 对象

平分两个页面

<html>
<frameset id="myFrameset" cols="50%,50%">
  <frame id="leftFrame" src="frame_a_noresize.htm">
  <frame id="rightFrame" src="frame_a.htm">
</frameset>
</html>

<html>
<head>
<script type="text/javascript">
function disableResize()
{
parent.document.getElementById("leftFrame").noResize=true
parent.document.getElementById("rightFrame").noResize=true
}
function enableResize()
{
parent.document.getElementById("leftFrame").noResize=false
parent.document.getElementById("rightFrame").noResize=false
}
</script>
</head>

<body bgcolor="#EFE7D6">
<form>
<input type="button" onclick="disableResize()" value="No resize">
<input type="button" onclick="enableResize()" value="Resize">
</form>
<p>Try to resize the frame.</p>
<p>Right-click inside the two frames and select "View Source" to see the source code.</p>
</body>

</html>


是否显示滚动条

<html>
<frameset id="myFrameset" cols="50%,50%">
  <frame id="leftFrame" src="frame_a_scrolling.htm">
  <frame id="rightFrame" src="frame_a.htm">
</frameset>
</html>

<html>
<head>
<script type="text/javascript">
function enableScrolling()
{
parent.document.getElementById("leftFrame").scrolling="yes"
parent.document.getElementById("rightFrame").scrolling="yes"
}
function disableScrolling()
{
parent.document.getElementById("leftFrame").scrolling="no"
parent.document.getElementById("rightFrame").scrolling="no"
}
</script>
</head>

<body bgcolor="#EFE7D6">
<form>
<input type="button" onclick="enableScrolling()" value="Scroll bars">
<input type="button" onclick="disableScrolling()" value="No scroll bars">
</form>
<p>Right-click inside the frames and select "View Source" to see the source code.</p>
</body>

</html>


改变页面的地址:

<html>
<frameset id="myFrameset" cols="50%,50%">
  <frame id="leftFrame" src="frame_a_src.htm">
  <frame id="rightFrame" src="frame_a.htm">
</frameset>
</html>

<html>
<head>
<script type="text/javascript">
function newSrc()
{
parent.document.getElementById("leftFrame").src="default.asp"
parent.document.getElementById("rightFrame").src="http://www.w3schools.com"
}
</script>
</head>

<body bgcolor="#EFE7D6">
<form>
<input type="button" onclick="newSrc()" value="Change frame source">
</form>
<p>Right-click inside the two frames and select "View Source" to see the source code.</p>
</body>

</html>

跳出框架

<html>
<head>
<script type="text/javascript">
function breakout()
{
if (window.top!=window.self)
 {
 window.top.location="tryjs_breakout.htm"
 }
}
</script>
</head>

<body>
<form>
Click the button to break out of the frame:
<input type="button" onclick="breakout()" value="Break out!">
</form>
</body>

</html>

更新两个页面

<html>
<frameset rows="25%,*" frameborder="1">
  <frame name="upperframe" src="frame_a.htm">
  <frame name="lowerframe" src="frames_sourcepage.htm">
</frameset>
</html>

<html>
<head>
<script type="text/javascript">
function changeurl()
{
parent.upperframe.location.href="frame_b.htm"
parent.lowerframe.location.href="frame_c.htm"
}
</script>
</head>
<body>

<form>
<input type="button" onclick="changeurl()" value="Change url">
</form>
<p>Right-click inside the two frames and select "View Source" to see the source code.</p>
</body>

</html>

更新2个以上的页面

<html>
<frameset cols="70%,*" frameborder="1">
  <frame src="frames_sourcepage2.htm">
  <frameset rows="30%,*" frameborder="1">
    <frame name="uframe" src="frame_a.htm">
    <frame name="lframe" src="frame_b.htm">
  </frameset>
</frameset>
</html>

<html>
<head>
<script type="text/javascript">
function changeurl()
{
parent.uframe.location.href="frame_c.htm"
parent.lframe.location.href="frame_d.htm"
}
</script>
</head>

<body>
<form>
<input type="button" value="Change url" onclick="changeurl()">
</form>
<p>Right-click inside the three frames and select "View Source" to see the source code.</p>
</body>

</html>

更新两个IFRAME

<html>
<head>
<script type="text/javascript">
function twoframes()
{
document.all("frame1").src="frame_c.htm"
document.all("frame2").src="frame_d.htm"
}
</script>
</head>

<body>
<iframe src="frame_a.htm" name="frame1"></iframe>
<iframe src="frame_b.htm" name="frame2"></iframe>
<br />
<form>
<input type="button" onclick="twoframes()" value="Change url of the two iframes">
</form>
</body>

</html>


图象对象

改变图象的高度

<html>
<head>
<script type="text/javascript">
function setHeight()
{
var x=document.images
x[0].height="250"
}
</script>
</head>

<body>
<img src="compman.gif" width="107" height="98" />
<form>
<input type="button" onclick="setHeight()" value="Change height of image">
</form>
</body>

</html>


改变图象

<html>
<head>
<script type="text/javascript">
function setSrc()
{
var x=document.images
x[0].src="hackanm.gif"
}
</script>
</head>

<body>
<img src="compman.gif" width="107" height="98" />
<form>
<input type="button" onclick="setSrc()" value="Change image">
</form>
</body>

</html>


改变图象的宽度

<html>
<head>
<script type="text/javascript">
function setWidth()
{
var x=document.images
x[0].width="300"
}
</script>
</head>

<body>
<img src="compman.gif" width="107" height="98" />
<form>
<input type="button" onclick="setWidth()" value="Change Width">
</form>
</body>

</html>


定位:

显示当前页的地址和改变当前页的地址

<html>
<head>
<script type="text/javascript">
function curr_Location()
{
alert(location)
}
function change_Location()
{
window.location="http://www.w3schools.com"
}
</script>
</head>

<body>
<form>
<input type="button" onclick="curr_Location()" value="Show current URL">
<input type="button" onclick="change_Location()" value="Change URL">
</form>
</body>

</html>


刷新页面

<html>
<head>
<script type="text/javascript">
function refresh()
{
window.location.reload()
}
</script>
</head>

<body>
<form>
<input type="button" value="Refresh page" onclick="refresh()">
</form>
</body>

</html>

导航对象


检测你的浏览器

<html>

<body>
<script type="text/javascript">
document.write("You are browsing this site with: "+ navigator.appName)
</script>
</body>

</html>


显示浏览器更加详细的信息

<html>
<body>
<script type="text/javascript">
document.write("<p>Browser: ")
document.write(navigator.appName + "</p>")

document.write("<p>Browserversion: ")
document.write(navigator.appVersion + "</p>")

document.write("<p>Code: ")
document.write(navigator.appCodeName + "</p>")

document.write("<p>Platform: ")
document.write(navigator.platform + "</p>")

document.write("<p>Cookies enabled: ")
document.write(navigator.cookieEnabled + "</p>")

document.write("<p>Browser's user agent header: ")
document.write(navigator.userAgent + "</p>")
</script>
</body>
</html>

最详细的浏览器的信息

<html>
<body>

<script type="text/javascript">
var x = navigator
document.write("CodeName=" + x.appCodeName)
document.write("<br />")
document.write("MinorVersion=" + x.appMinorVersion)
document.write("<br />")
document.write("Name=" + x.appName)
document.write("<br />")
document.write("Version=" + x.appVersion)
document.write("<br />")
document.write("CookieEnabled=" + x.cookieEnabled)
document.write("<br />")
document.write("CPUClass=" + x.cpuClass)
document.write("<br />")
document.write("OnLine=" + x.onLine)
document.write("<br />")
document.write("Platform=" + x.platform)
document.write("<br />")
document.write("UA=" + x.userAgent)
document.write("<br />")
document.write("BrowserLanguage=" + x.browserLanguage)
document.write("<br />")
document.write("SystemLanguage=" + x.systemLanguage)
document.write("<br />")
document.write("UserLanguage=" + x.userLanguage)
</script>

</body>
</html>


按浏览器不同实现导航

<html>
<head>
<script type="text/javascript">
function redirectme()
{
bname=navigator.appName
if (bname.indexOf("Netscape")!=-1)
 {
 window.location="tryjs_netscape.htm"
 return
 }
if (bname.indexOf("Microsoft")!=-1)
 {
 window.location="tryjs_microsoft.htm"
 return
 }
window.location="tryjs_other.htm"
}
</script>
</head>
<body "redirectme()">
</body>
</html>


检测浏览器的版本

<html>
<head>
<script type="text/javascript">
function browserversion()
{
txt="Your browser is unknown"
browser=navigator.appVersion
if (browser.indexOf("2.")>-1)
{
txt="Your browser is from the stone-age!"
}
if (browser.indexOf("3.")>-1)
{
txt="You should update your browser!"
}
if (browser.indexOf("4.")>-1)
{
txt="Your browser is good enough!"
}
document.getElementById("message").innerHTML=txt
}
</script>
</head>

<body "browserversion()">
<span id="message"></span>
</body>

</html>

选择对象

设置下拉列表的可用性

<html>
<head>
<script type="text/javascript">
function makeDisable()
{
var x=document.getElementById("mySelect")
x.disabled=true
}
function makeEnable()
{
var x=document.getElementById("mySelect")
x.disabled=false
}
</script>
</head>

<body>
<form>
<select id="mySelect">
 <option>Apple</option>
 <option>Banana</option>
 <option>Orange</option>
</select>
<input type="button" onclick="makeDisable()" value="Disable list">
<input type="button" onclick="makeEnable()" value="Enable list">
</form>
</body>

</html>

返回下拉列表中选择的项的值

<html>
<head>
<script type="text/javascript">
function formAction()
{
var x=document.getElementById("mySelect")
alert(x.length)
}
</script>
</head>

<body>
<form>
<select id="mySelect">
 <option>Apple</option>
 <option>Banana</option>
 <option>Orange</option>
</select>
<input type="button" onclick="formAction()" value="How many options in the list?">
</form>
</body>
</html>

改变下拉列表的大小

<html>
<head>
<script type="text/javascript">
function formAction()
{
var x=document.getElementById("mySelect")
x.size="3"
}
</script>
</head>

<body>
<form>
<select name="mySelect">
 <option>Apple</option>
 <option>Banana</option>
 <option>Orange</option>
 <option>Melon</option>
</select>
<input type="button" onclick="formAction()" value="Change size of list">
</form>
</body>

</html>


列表可选择多项

<html>
<head>
<script type="text/javascript">
function formAction()
{
var x=document.getElementById("mySelect")
x.multiple=true
}
</script>
</head>

<body>
<p>
Before you click on the "Select multiple" button, try to select more than one option (by holding down the shift or Ctrl key). Click on the "Select multiple" button and try again.
</p>
<form>
<select name="mySelect" size="3">
 <option>Apple</option>
 <option>Banana</option>
 <option>Orange</option>
</select>
<input type="button" onclick="formAction()" value="Select multiple">
</form>
</body>

</html>


返回所选列表的文本值

<html>
<head>
<script type="text/javascript">
function getText()
{
var x=document.getElementById("mySelect")
alert(x.options[x.selectedIndex].text)
}
</script>
</head>

<body>
<form>
Select your favorite fruit:
<select id="mySelect">
 <option>Apple</option>
 <option>Orange</option>
 <option>Pineapple</option>
 <option>Banana</option>
</select>
<br /><br />
<input type="button" onclick="getText()" value="Show text of selected fruit">
</form>
</body>

</html>


删除列表的项目

<html>
<head>
<script type="text/javascript">
function formAction()
{
var x=document.getElementById("mySelect")
x.remove(x.selectedIndex)
}
</script>
</head>

<body>
<form>
<select name="mySelect">
 <option>Apple</option>
 <option>Banana</option>
 <option>Orange</option>
</select>
<input type="button" onclick="formAction()" value="Remove option">
</form>
</body>

</html>


显示屏幕的信息

<html>
<body>
<script type="text/javascript">
document.write("Screen resolution: ")
document.write(screen.width + "*" + screen.height)
document.write("<br />")
document.write("Available view area: ")
document.write(screen.availWidth + "*" + screen.availHeight)
document.write("<br />")
document.write("Color depth: ")
document.write(screen.colorDepth)
document.write("<br />")
</script>
</body>
</html>


表格对象

改变表格的边框

<html>
<head>
<script type="text/javascript">
function changeBorder()
{
document.getElementById('myTable').border="10"
}
</script>
</head>

<body>
<table border="1" id="myTable">
<tr>
<td>100</td>
<td>200</td>
</tr>
<tr>
<td>300</td>
<td>400</td>
</tr>
</table>
<form>
<input type="button" onclick="changeBorder()" value="Change Border">
</form>
</body>

</html>


改变表格的间距

<html>
<head>
<script type="text/javascript">
function padding()
{
document.getElementById('myTable').cellPadding="15"
}
function spacing()
{
document.getElementById('myTable').cellSpacing="15"
}
</script>
</head>
<body>

<table id="myTable" border="1">
<tr>
<td>100</td>
<td>200</td>
</tr>
<tr>
<td>300</td>
<td>400</td>
</tr>
</table>
<form>
<input type="button" onclick="padding()" value="Change Cellpadding">
<input type="button"

 设置或获取对象指定的文件名或路径。
<script>
alert(window.location.pathname)
</script>

设置或获取整个 URL 为字符串。
<script>

alert(window.location.href);
</script>
设置或获取与 URL 关联的端口号码。
<script>
alert(window.location.port)
</script>

设置或获取 URL 的协议部分。
<script>
alert(window.location.protocol)
</script>

设置或获取 href 属性中在井号“#”后面的分段。
<script>
alert(window.location.hash)
</script>

设置或获取 location 或 URL 的 hostname 和 port 号码。
<script>
alert(window.location.host)
</script>

设置或获取 href 属性中跟在问号后面的部分。
<script>
alert(window.location.search)
</script>

 

AJAX指南(2)---- 操作XML
作者:张元一(zhangyuanyi@gmail.com
日期:2005-12-19
本人才疏学浅,错误和疏漏在所难免,欢迎大家批评指正。

    通过上一章的学习,我们已经对AJAX的工作原理有了一个基本的了解,但是上一章的例子中并没有用到AJAX中很重要的一个组件XML,所以上一章的例子最多只能称为AJAH(HTML)或者干脆就是AJAT(TEXT),因此这一章我们就来学习如何使用AJAX操作XML。

    同上一章一样,首先我们需要创建一个XMLHttp对象:

          var http = getHTTPObject();

    假设我们有一个XML文件mailbox.xml,它的内容如下:

          <?xml version="1.0" encoding="GB2312"?>
          <mailbox>
                <mail>
                    <to>老李</to>
                    <from>老张</from>
                    <heading>好久不见!</heading>
                    <body>好久不见,最近好吗?</body>
                </mail>
                <mail>
                    <to>小李</to>
                    <from>小王</from>
                    <heading>周末有空么?</heading>
                    <body>周末有空么?一起看场电影吧!</body>
                </mail>
          </mailbox>

    可以看到,里面存储了两封邮件,现在我们的目标就是把这两封邮件以HTML的方式展现出来,首先我们需要创建一个简单的HTML的界面:

          <p><button onclick="loadXMLDoc('bookshelf.xml', parseBookShelf)">查看书架</button></p>
          <div id="ajax-sample"></div>

    ajax-sample块用于展示邮件,但查看信箱按钮被按下时,loadXMLDoc函数将被调用:

          function loadXMLDoc(name, parseFunc)
          {
                http.open("GET", name, true);
                http.onreadystatechange = parseFunc;
                http.send(null);
          }

    可以看到,这个函数只是简单的向服务器发送一个GET请求,真正对XML文档进行处理的是parseFunc,也就是我们传入的parseMailBox函数:

          function parseMailBox()
          {
                //4表示请求已完成
                if (http.readyState == 4) {
                    //responseXML是一个HTML DOM Document对象,
                    //我们将使用它来解析XML文档
                    var mailBoxXML = http.responseXML;
                    //获取所有信件
                    var mails = mailBoxXML.getElementsByTagName('mail');
                    var mailStr = "";

                    for (var i = 0; i < mails.length; i++) {
                          var mail = mails;

                          //解析信件
                          var to = getElementText(mail, "to");
                          var from = getElementText(mail, "from");
                          var heading = getElementText(mail, "heading");
                          var body = getElementText(mail, "body");

                          //为信件添加附属信息
                          mailStr += "收信人:" + to + "<br>";
                          mailStr += "发信人:" + from + "<br>";
                          mailStr += "标题:" + heading + "<br>";
                          mailStr += "正文:<br>" + body + "<br><br>";
                    }
                    //将信件展示到页面上
                    document.getElementById("ajax-sample").innerHTML = mailStr;
                }
          }

    getElemenText函数相当简单,它的作用就是获取一个元素的文本:

          function getElementText(parentElem, name)
          {
                var result = parentElem.getElementsByTagName(name)[0];
                return result.firstChild.nodeValue;
          }

    这样一个XML文档就解析完毕了,是不是相当的简单。

更多日志..