Javascript有事件来提供网页的动态界面。这些事件连接到文档对象模型(DOM)中的元素。 默认情况下,这些事件使用冒泡传播,即在DOM中从子级向上传播到父级。我们可以将事件绑定为内联或外部脚本。 以下是一些javascript事件: 1) onclick事件: 这是一个鼠标事件,如果用户单击它绑定到的元素,就会触发任何定义的逻辑。 代码#1:
html
<!doctype html> < html > < head > < script > function hiThere() { alert('Hi there!'); } </ script > </ head > < body > < button type = "button" onclick = "hiThere()" >Click me event</ button > </ body > </ html > |
输出: 在点击“点击我事件”键之前-
点击“点击我事件”键后-
2) onkeyup事件: 此事件是一个键盘事件,在按下后释放按键时执行指令。 代码#2:
html
<!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 += 1; b += a + 1; c += b + 1; if (a > 255) a = a - b; if (b > 255) b = a; if (c > 255) c = b; } </ script > </ head > < body > < input id = "bg" onkeyup = "changeBackground()" placeholder = "write something" style = "color:#fff" > </ body > </ html > |
输出: 在写“gfg”之前-
在写了《gfg》之后-
3) onmouseover活动: 此事件对应于将鼠标指针悬停在元素及其绑定到的子元素上。 代码#3:
html
<!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 > |
输出: 在老鼠占领绿色广场之前-
当鼠标移到绿色方块上后,它就消失了。 4) onmouseout活动: 每当鼠标光标离开处理mouseout事件的元素时,就会执行与其关联的函数。 代码#4:
html
<!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 > |
输出: 在老鼠占领绿色广场之前-
一段时间后,鼠标移到绿色方块上,绿色方块就会消失。 5) onchange事件: 此事件检测列出此事件的任何元素的值的变化。 代码#5:
html
<!doctype html> < html > < head ></ head > < body > < input onchange = "alert(this.value)" type = "number" > </ body > </ html > |
输出: 在按下任何键之前-
按下2键后-
6) 加载事件: 当一个元素被完全加载时,该事件被触发。 代码#6:
html
<!doctype html> < html > < head ></ head > < body > < img onload = "alert('Image completely loaded')" alt = "GFG-Logo" </ body > </ html > |
输出:
7) onfocus活动: 每当接收到焦点时,列出此事件的元素就会执行指令。 代码#7:
html
<!doctype html> <!doctype html> < html > < head > < script > function focused() { var e = document.getElementById('inp'); if (confirm('Got it?')) { e.blur(); } } </ script > </ head > < body > < p >Take the focus into the input box below:</ p > < input id = "inp" onfocus = "focused()" > </ body > </ html > |
输出: 在框内单击鼠标之前-
在框内单击鼠标后-
8) onblur事件: 当一个元素失去焦点时,会触发此事件。 代码#8:
html
<!doctype html> < html > < head ></ head > < body > < p >Write something in the input box and then click elsewhere in the document body.</ p > < input onblur = "alert(this.value)" > </ body > </ html > |
输出: 在框内输入“gfg”之前-
在框内输入“gfg”并按enter键后-
附言: 鼠标放开 事件侦听鼠标左键和中键单击,但 上下 事件侦听鼠标左键、中键和右键单击 onclick 只处理左键单击。