常见事件:
- 单击
- 双击
- 聚焦(当鼠标点击输入框时)
- 失焦 (当鼠标从输入框中移除并点击其他位置时)
- 选项改变 (单选或多选时切换选项)
- 鼠标移动
- 鼠标移除
- 标签内容加载完成
<title>无标题文档</title>
<style type="text/css">
div{
background:#F00;
width:100px;
height:100px;
}
</style>
<script type="text/javascript">
//测试单击
function testClick(){
alert("触发单击事件");
}
//测试双击
function testDBClick(){
alert("触发双击事件");
}
//测试聚焦
function testFocus(){
var userName = document.getElementById("userName");
userName.value = "";
/*
不能像下面这样直接用获取的valu来赋值,这样无法达到修改该标签value的目的
var userName = document.getElementById("userName").value;
userName = "";
*/
}
//测试失焦
function testBlur(){
//alert("来啦");
var userName = document.getElementById("userName").value;
var prompt = document.getElementById("userNameprompt");
if (userName == "丁昌江"){
prompt.innerHTML = "已存在该用户名,请重新输入";
prompt.style.color="red"; //任务标签都有的属性style
}else{
prompt.innerHTML = "恭喜,该用户名可以注册";
prompt.style.color="green";
}
}
//测试选项改变
function testChange(){
var province = document.getElementById("province");
//alert("您选择的是:"+province.value);//selection的value就是选中的option的值
var city = document.getElementById("city");
city.innerHTML = "";
if (province.value == "贵州"){
var cityArr = ["贵阳","凯里","都匀"]
for (var i=0;i<cityArr.length;i++){
city.innerHTML+=("<option>"+cityArr[i]+"</option>");
}
}
if (province.value == "广东"){
var cityArr = ["广州","深圳","东莞"]
for (var i=0;i<cityArr.length;i++){
city.innerHTML+=("<option>"+cityArr[i]+"</option>");
}
}
if (province.value == "江西"){
var cityArr = ["南昌","抚州","九江"]
for (var i=0;i<cityArr.length;i++){
city.innerHTML+=("<option>"+cityArr[i]+"</option>");
}
}
}
//测试鼠标经过
function testMouseMove(){
alert("鼠标到了");
}
//测试鼠标移除
function testMouseOut(){
alert("鼠标移走啦!");
}
//页面加载相关 onload()
function testOnLoad(){
alert("body标签的内容加载完啦!");
}
</script>
</head>
<body onload="testOnLoad()"> <!--当body标签中的内容都加载完毕会触发load方法-->
<input type="button" value="单击测试" onclick="testClick()"/>
<input type="button" value="双击测试" ondblclick="testDBClick()"/>
<hr/>
姓名:
<input type="text" id="userName" value="请输入4-12位字符" onfocus="testFocus()" onblur="testBlur()"/>
<span id="userNameprompt"></span>
<hr/>
你在哪卖?<br />
<select id="province" onchange="testChange()">
<option>贵州</option>
<option>广东</option>
<option>江西</option>
</select>
<select id="city">
<option>贵阳</option>
<option>凯里</option>
<option>都匀</option>
</select>
<hr/>
<div onmouseover="testMouseMove()" onmouseout="testMouseOut()"></div>
</body>