最近在学习JavaWeb时,有用到鼠标移动事件,所以今天在这里记录一个相关的案例,同时也是对相关知识的一个巩固,效果为在鼠标移动到表格对应行列时,该行列的背景颜色发生变化。
效果如下:
其中用到是onmouseover和onmouseou事件t,同时还有一个作用相似的事件叫做onmousemove,所以在这里先对这三种鼠标事件做一个简单的对比:
onmouseout事件则是在鼠标移出对象区域时触发。
搞懂这三者之间的关系,在进行鼠标经过事件的处理时只需使用对应的事件触发即可:
接下来是对上述事件和效果的代码:
Jsp部分代码:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>" rel="external nofollow" > <title>表格颜色变化</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" > --> <script type="text/javascript" src="index.js"></script> </head> <body> <table width = "200" border = "1" align = "center" cellpadding="1" cellspacing="5"> <tr id = "t0"><th>学校</th><th>专业</th><th>人数</th></tr> <tr id = "t1"><th>济大</th><th>软件</th><th>2000</th></tr> <tr id = "t2"><th>北大</th><th>机械</th><th>3000</th></tr> <tr id = "t3"><th>浙大</th><th>生物</th><th>4000</th></tr> </table> </body> </html>
Js部分代码:
onload = function() { var t0 = document.getElementById("t0"); var t1 = document.getElementById("t1"); var t2 = document.getElementById("t2"); var t3 = document.getElementById("t3"); t0.onmouseover = function () { t0.style.backgroundColor = "green"; } t0.onmouseout = function () { t0.style.backgroundColor = "white"; } t1.onmouseover = function () { t1.style.backgroundColor = "red"; } t1.onmouseout = function () { t1.style.backgroundColor = "white"; } t2.onmouseover = function () { t2.style.backgroundColor = "red"; } t2.onmouseout = function () { t2.style.backgroundColor = "white"; } t3.onmouseover = function () { t3.style.backgroundColor = "red"; } t3.onmouseout = function () { t3.style.backgroundColor = "white"; } }