Javascript常用事件总结

1、onload和onunload事件。

onload和onunload会在用户进入和离开页面的时候触发。

例如:onload会在页面页面成功加载完成之后弹出来一个消息框。

<body onload="mymessage()">
<script>
	function mymessage(){
	alert("消息在 onload 事件触发后弹出。");
}
</script>
<p>成功进入</p>
</body>

用onunload尝试多次均未弹出消息框,浏览器把这个功能废弃啦?

2、onchange事件

常结合对输入字段的验证来使用。
例如:当用户改变输入字段的内容时,调用toUpperCase()函数。

<head>
<script>
function myfunction(){
	var x=document.getElementById("info");
	x.value=x.value.toUpperCase();
}
</script>
</head>
<body>
<input type="text" id="info" onchange="myfunction()">
<p>当离开输入框时,函数将被触发,将小写字母转化为大写字母</p>
</body>

3、onmouseover和onmouseout事件。

onmouseover是将鼠标移动上来之后发生一些变化。
onmouseout是将鼠标移走后发生的一些变化。

<!DOCTYPE>
<html>
<head>
<meta charset="utf-8">
<title>动态变化</title>
<script>
	function over(id){
		id.innerHTML="Oh,Nice!";
		id.style.color="red";
	}
	function out(id){
		id.innerHTML="Oh,Bye!";
	}
</script>
</head>
<body>
	<div onmouseover="over(this)" onmouseout="out(this)" style="background-color:#666;width:30%;height:100px;line-height:100px;text-align:center;font-size:5em;">Come on!</div>
</body>
</html>

4、onmousedown,onmouseup和onclick事件。

onmousedown,onmouseup,onclick构成了鼠标点击事件的所有部分。首先当点击鼠标按钮时,会触发onmousedown事件,当释放鼠标按钮时,会触发onmouseup事件,最后,当完成鼠标点击时,会触发onclick事件。

<!DOCTYPE>
<html>
<head>
<meta charset="utf-8">
<title>动态变化</title>
<script>
	function over(id){
		
		id.style.color="red";
		id.innerHTML="Oh,Nice!";
	}
	function out(id){
		id.innerHTML="Oh,Bye!";
		id.style.background="blue";
	}
	function cl(id){
		id.innerHTML="Come on!";
		id.style.color="#eee";
		id.style.background="#666";
	}
</script>
</head>
<body>
	<div onmousedown="over(this);" onmouseup="out(this);" onclick="cl(this)" style="background-color:#666;width:30%;height:100px;line-height:100px;text-align:center;font-size:5em;color:#eee;">Come on!</div>  //字体颜色直接用color
</body>
</html>

字体颜色在style里面直接用color,用font-color不管用。

在这里也可以发现,onmouseup和onclick是重复的(会覆盖掉),写一个就行。

5、onfocus事件。

当输入字段获得焦点时,改变其属性。
(当输入框获取焦点时,改变其背景颜色)

<!DOCTYPE>
<html>
<head>
<meta charset="utf-8">
<script>
	function foc(id){
		id.style.background="blue";
	}
</script>
</head>
<body>
<input type="text" onfocus="foc(this)">
</body>
</html>

背景颜色,用background控制,而不是background-color。

猜你喜欢

转载自blog.csdn.net/sun9979/article/details/85210481