JavaScript常见的一些事件:
- onchange事件多用于可输入的内容的元素,当内容改变的时候会触发该事件
案例:效果 是 当 选中 下拉框 中的内容时会跳转到指定页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<select name="" onchange="on()" id="1">
<option value="http:\\www.baidu.com" >百度</option>
<option value="http:\\www.163.com">网易</option>
<option value="http:\\www.qq.com" >腾讯</option>
</select>
<script type="text/javascript">
function on(){
var url=document.getElementById("1").value;
//window.location.href=url;
window.open(url);
}
</script>
</html>
- onclick是绑定事件,告诉浏览器在鼠标点击时候要做什么。
案例效果:点击button按钮时 ,出现当前时间
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button onclick="displayDate()">点这里</button>
</body>
<script>
function displayDate(){
document.getElementById("demo").innerHTML=Date();
// innerHTML在JS是双向功能:一、获取对象的内容 二、 向对象插入内容;
// Date方法可返回当天的日期和时间
}
</script>
<p id="demo"></p>
</html>
click与onclick的区别
click本身是方法作用是触发onclick事件,只要执行了元素的click()方法,就会触发onclick事件
- onmouseover 在一个HTML元素上移动鼠标
案例效果:当鼠标移入到指定的位置时 显示"已经触发"的文字
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button onmouseover="f()">移入</button>
<p id="t"></p>
</body>
<script>
function f() {
document.getElementById("t").innerHTML="已经触发";
}
</script>
</html>
- onmouseout在一个HTML元素上移开鼠标
案例效果:当鼠标移出button按钮时,显示"已经触发"的文字
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button onmouseout="f()">移入</button>
<p id="t"></p>
</body>
<script>
function f() {
document.getElementById("t").innerHTML="已经触发";
}
</script>
</html>
- onkeydown 按下键盘按键
案例效果:当在输入框中 输入键盘的如何键都会触发事件,显示"已经触发"的文字
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" onkeydown="f()">
<p id="t"></p>
</body>
<script>
function f() {
document.getElementById("t").innerHTML="已经触发";
}
</script>
</html>
- onload 浏览器已完成页面的加载
案例效果:当函数f()执行完 里面的内容的时候 触发onload显示,h1标签中的内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body onload="f()">
<h1>页面加载完成显示的页面内容</h1>
</body>
<script>
function f() {
alert("加载成功")
}
</script>
</html>