两个函数帮助我们捕捉鼠标点击:onmousedown与onmouseup.当我们获取document.onmousedown时,我们同时获取了任何对象的点击属性如:text,images,tables等等.我们只想获取那些需要的属性,所以我们设置函数来获取。
document.onmouseup = mouseUp; var dragObject = null; function makeClickable(item) { if (!item) return; item.onmousedown = function(ev) { dragObject = this; } } function mouseUp(ev) { dragObject = null; }
dragObject 变量就是鼠标点击的对象,鼠标弹起时候,该对象便为空。
示例:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
legend {
font-weight: bold;
font-size: 12px;
color: #666699;
font-family: verdana, tahoma, arial;
}
fieldset {
padding: 3px;
}
</style>
<title>点击</title>
<script type="text/javascript">
window.onload = function()
{
makeClickable($('ClickImage1'));
makeClickable($('ClickImage2'));
makeClickable($('ClickImage3'));
makeClickable($('ClickImage4'));
}
document.onmouseup = mouseUp;
var dragObject = null;
function makeClickable(item)
{
if (!item)
return;
item.onmousedown = function(ev)
{
//dragObject = this;
$('ClickImage').value = this.name;
}
}
function mouseUp(ev)
{
dragObject = null;
}
function $(id)
{
return document.getElementById(id);
}
</script>
</head>
<body>
<fieldset id="Demo">
<legend>示例 - 点击图标</legend>
<img id="ClickImage1" src="images/spade.gif" name="黑桃">
<img id="ClickImage2" src="images/heart.gif" name="红星">
<img id="ClickImage3" src="images/diamond.gif" name="方块">
<img id="ClickImage4" src="images/club.gif" name="梅花"> <br>
你单击: <input id="ClickImage">
</fieldset>
</body>
</html>
效果:
点击什么,出什么。呵呵