JavaScript 事件
Javascript 具有事件来为网页提供动态界面。这些事件是通过将其与文档对象模型(DOM)中的元素关联起来。
这些事件默认使用冒泡传播,即从子元素向父元素向上传播。我们可以将事件与元素绑定,无论是内联还是外部脚本。
语法:
<HTML-element Event-Type = "Action to be performed">
以下是一些JavaScript事件:
JavaScript onclick事件
这是一个鼠标事件,如果用户点击绑定的元素,就会引发任何定义的逻辑。
示例: 在这个示例中,当按钮被点击时,我们将在警告框中显示一条消息。
<!doctype html>
<html>
<head>
<script>
function hiThere() {
alert('Hi there!');
}
</script>
</head>
<body>
<button type="button"
onclick="hiThere()"
style="margin-left: 50%;">
Click me event
</button>
</body>
</html>
输出:

JavaScript onkeyup事件
此事件是键盘事件,当按键释放时执行指令。
示例: 在此示例中,我们将通过按下向上箭头键来改变颜色。
<!doctype html>
<html>
<head>
<script>
var a=0;
var b=0;
var c=0;
function changeBackground() {
var x=document.getElementById('bg');
x.style.backgroundColor='rgb('+a+', '+b+', '+c+')';
a+=100;
b+=a+50;
c+=b+70;
if(a>255) a=a-b;
if(b>255) b=a;
if(c>255) c=b;
}
</script>
</head>
<body>
<h4>The input box will change color when UP arrow key is pressed</h4>
<input id="bg" onkeyup="changeBackground()" placeholder="write something" style="color:#fff">
</body>
</html>
输出:

JavaScript onmouseover事件
该事件对应于将鼠标指针悬停在该元素及其子元素上的情况,它绑定在元素上。
示例: 在这个示例中,当鼠标悬停在盒子上时,我们将使其消失。
<!doctype html>
<html>
<head>
<script>
function hov() {
var e=document.getElementById('hover');
e.style.display='none';
}
</script>
</head>
<body>
<div id="hover"
onmouseover="hov()"
style="background-color:green;
height:200px;
width:200px;">
</div>
</body>
</html>
输出:

JavaScript onmouseout事件
当鼠标光标离开处理mouseout事件的元素时,与之相关的函数将被执行。
示例:
<!doctype html>
<html>
<head>
<script>
function out() {
var e=document.getElementById('hover');
e.style.display='none';
}
</script>
</head>
<body>
<div id="hover" onmouseout="out()" style="background-color:green;height:200px;width:200px;">
</div>
</body>
</html>
输出:

JavaScript onchange事件
此事件检测与此事件监听的任何元素的值变化。
示例:
<!doctype html>
<html>
<head></head>
<body>
<input onchange="alert(this.value)"
type="number"
style="margin-left: 45%;">
</body>
</html>
输出:

JavaScript onload事件
当一个元素完全加载完成时,会触发此事件。
示例:
<!doctype html>
<html>
<head></head>
<body>
<img onload="alert('Image completely loaded')"
alt="GFG-Logo"
src=
"https://media.geeksforgeeks.org/wp-content/cdn-uploads/GeeksforGeeksLogoHeader.png">
</body>
</html>
输出:

JavaScript onfocus事件
当一个元素监听该事件时,它会在接收到焦点时执行指令。
示例:
<!doctype html>
<!doctype html>
<html>
<head>
<script>
function focused() {
var e=document.getElementById('inp');
if(confirm('Got it?')) {
e.blur();
}
}
</script>
</head>
<body>
<p style="margin-left: 45%;">
Take the focus into the input box below:
</p>
<input id="inp"
onfocus="focused()""
style=" margin-left: 45%;">
</body>
</html>
输出:

JavaScript onblur事件
当元素失去焦点时触发此事件。
示例:
<!doctype html>
<html>
<head></head>
<body style="margin-left: 40%;">
<p>Write something in the input box and then click elsewhere
in the document body.</p>
<input onblur="alert(this.value)">
</body>
</html>
输出:

提示: JavaScript中的 onmouseup 事件监听左键和中键的点击,而onmousedown事件监听左键、中键和右键的点击,而 onclick 只处理左键点击。
极客教程