1. 程式人生 > 程式設計 >Javaweb 滑鼠移入移出表格顏色變化的實現

Javaweb 滑鼠移入移出表格顏色變化的實現

最近在學習JavaWeb時,有用到滑鼠移動事件,所以今天在這裡記錄一個相關的案例,同時也是對相關知識的一個鞏固,效果為在滑鼠移動到表格對應行列時,該行列的背景顏色發生變化。

效果如下:

Javaweb 滑鼠移入移出表格顏色變化的實現

其中用到是onmouseover和onmouseou事件t,同時還有一個作用相似的事件叫做onmousemove,所以在這裡先對這三種滑鼠事件做一個簡單的對比:

  • 在時間上:如果兩個事件同時存在,先是onmousemove事件觸發後,才會觸發onmouseover事件。
  • 在按鈕上:onmousemove和onmouseover都不區分滑鼠按鈕
  • 在動作上:onmouseover是在滑鼠剛移入區域的時候觸發,onmousemove是除了滑鼠移入區域時觸發外,滑鼠在區域內移動同樣也會觸發事件。
  • 兩者區別:當滑鼠移過當前物件區域時就產生了onmouseover事件,所以onmouseover事件有個移入移出的過程,當滑鼠在當前物件區域上移動時就產生了onmousemove事件,只要是在物件上移動而且沒有移出物件的,那麼就是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";
  }
}

到此這篇關於Javaweb 滑鼠移入移出表格顏色變化的實現的文章就介紹到這了,更多相關Javaweb 滑鼠移入移出表格內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!