js常用事件及其用法

1.onload 和 onunload 事件

onload事件:指的是页面加载事件。

 onunload事件:指的是离开页面事件

<!DOCTYPE html>
<html>
<body onload="test()">

<script>
function test()
{
if (navigator.cookieEnabled==true)
    {
    alert("已启用 cookie")
    }
else
    {
    alert("未启用 cookie")
    }
}
</script>

<p>提示框会告诉你,浏览器是否已启用 cookie。</p>
</body>
</html>

2.onchange 事件

onchange 事件常结合对输入字段的验证来使用。

下面是一个如何使用 onchange 的例子。当用户改变输入字段的内容时,会调用 upperCase() 函数。

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
var x=document.getElementById("fname");
x.value=x.value.toUpperCase();
}
</script>
</head>
<body>

请输入英文字符:<input type="text" id="fname" onchange="myFunction()">
<p>当您离开输入字段时,会触发将输入文本转换为大写的函数。</p>

</body>
</html>

3.onmouseover 和 onmouseout 事件

onmouseover 和 onmouseout 事件可用于在用户的鼠标移至 HTML 元素上方或移出元素时触发函数。

<!DOCTYPE html>
<html>
<body>

<div onmouseover="mOver(this)" onmouseout="mOut(this)" style="background-color:green;width:120px;height:20px;padding:40px;color:#ffffff;">把鼠标移到上面</div>

<script>
function mOver(obj)
{
obj.innerHTML="谢谢"
}

function mOut(obj)
{
obj.innerHTML="把鼠标移到上面"
}
</script>

</body>
</html>

4.onmousedown、onmouseup 以及 onclick 事件

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

<!DOCTYPE html>
<html>
<body>

<div onmousedown="mDown(this)" onmouseup="mUp(this)" style="background-color:green;color:#ffffff;width:90px;height:20px;padding:40px;font-size:12px;">请点击这里</div>

<script>
function mDown(obj)
{
obj.style.backgroundColor="#1ec5e5";
obj.innerHTML="请释放鼠标按钮"
}

function mUp(obj)
{
obj.style.backgroundColor="green";
obj.innerHTML="请按下鼠标按钮"
}
</script>

</body>
</html>

 5.onfocus获取焦点事件。

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(x)
{
x.style.background="green";
}
</script>
</head>
<body>

请输入英文字符:<input type="text" onfocus="myFunction(this)">

<p>当输入字段获得焦点时,会触发改变背景颜色的函数。</p>

</body>
</html>

希望以上总结可以帮到大家。

posted @ 2016-04-08 13:10  心雨星空  阅读(572)  评论(0编辑  收藏  举报