JS入门到精通 第9章 事件处理
一、练习
1. 练习1
(1)源代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>通过按钮变换背景颜色</title>
</head>
<body>
<script type="text/javascript">
var Arraycolor=new Array("olive","teal","red","blue","maroon","navy","lime","fuschia","green","purple","gray","yellow","aqua","white","silver");
var n=0;
function turncolors(){
n++;
if (n==(Arraycolor.length-1)) n=0;
document.bgColor = Arraycolor[n];
}
</script>
<p>
<input type="button" name="Submit" value="变换背景" onclick="turncolors()">
</p>
</body>
</html>
(2)运行页面
https://www.xinyizhishu.top/jsC/sc/9_1/
(3)Tips
.bgcolor。
2. 练习2
(1)源代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>用事件制作超链接文本</title>
</head>
<body>
<p id="p1" style="color:#AA9900; cursor:pointer" onmousedown="mousedown()" onmouseup="mouseup()"><u>零基础学JavaScript</u></p>
<script type="text/javascript">
function mousedown(){
var obj=document.getElementById("p1");
obj.style.color='#0022AA';
}
function mouseup(){
var obj=document.getElementById('p1');//获取包含文本的元素
obj.style.color='#AA9900';//将文本恢复为原来的颜色
}
</script>
</body>
</html>
(2)运行页面
https://www.xinyizhishu.top/jsC/sc/9_2/
(3)Tips
简单的动起来。
3. 练习3
(1)源代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>鼠标移入移出时改变图片透明度</title>
</head>
<body>
<script type="text/javascript">
function visible(cursor,i){ //定义visible()函数
if (i==0) //如果参数i的值为0
cursor.style.opacity=1; //将图片不透明度设置为1
else
cursor.style.opacity=0.5;//将图片不透明度设置为0.5
}
</script>
<img src="images/Temp.jpg" onMouseOver="visible(this,1)" onMouseOut="visible(this,0)" />
</body>
</html>
(2)运行页面
https://www.xinyizhishu.top/jsC/sc/9_3/
(3)Tips
真的这么简单?
4. 练习4
(1)源代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>显示鼠标在页面中的当前位置</title>
</head>
<body>
<script type="text/javascript">
var x=0,y=0; //初始化变量的值
function MousePlace(event){
x=event.x; //获取横坐标X的值
y=event.y; //获取纵坐标Y的值
document.getElementById('position').innerHTML="鼠标在页面中的当前位置的横坐标X:"+x+" 纵坐标Y:"+y;
}
document.onmousemove=MousePlace;
</script>
<span id="position"></span>
</body>
</html>
(2)运行页面
https://www.xinyizhishu.top/jsC/sc/9_4/
(3)Tips
让浏览器自动监听。
5. 练习5
(1)源代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>按A键对页面进行刷新</title>
</head>
<body>
<script type="text/javascript">
function Refurbish(event){//定义Refurbish()函数
if (event.keyCode==75){//K键
location.reload();
}
}
document.onkeydown=Refurbish;//当按下键盘上的按键时调用函数
</script>
<img src="1.jpg" width="805" height="554">
</body>
</html>
(2)运行页面
https://www.xinyizhishu.top/jsC/sc/9_5/
(3)Tips
event.keyCode,location.reload()。