HTML--如何实现通过鼠标事件拖动页面图像(代码)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head><title>onMouseMove Event Handler</title>
<style type="text/css">
#camap {position:absolute; left:20; top:120}
#ormap {position:absolute; left:80; top:120}
#wamap {position:absolute; left:140; top:120}
</style>
</head>
<script type="text/javascript">
// global variables used while dragging
var offsetX = 0
var offsetY = 0
var selectedObj
var frontObj
// set document-level event handlers
document.onmousedown = engage
document.onmouseup = release
// positioning an object at a specific pixel coordinate
function shiftTo(obj, x, y) {
obj.style.pixelLeft = x
obj.style.pixelTop = y
}
// setting the z-order of an object
function bringToFront(obj) {
if (frontObj) {
frontObj.style.zIndex = 0
}
frontObj = obj
frontObj.style.zIndex = 1
}
// set global var to a reference to dragged element
function setSelectedObj() {
var imgObj = window.event.srcElement
if (imgObj.id.indexOf("map") == 2) {
selectedObj = imgObj
bringToFront(selectedObj)
return
}
selectedObj = null
return
}
// do the dragging (called repeatedly by onMouseMove)
function dragIt() {
if (selectedObj) {
shiftTo(selectedObj, (event.clientX - offsetX), (event.clientY - offsetY))
return false
}
}
// set global vars and turn on mousemove trapping (called by onMouseDown)
function engage() {
setSelectedObj()
if (selectedObj) {
document.onmousemove = dragIt
offsetX = window.event.offsetX - document.body.scrollLeft
offsetY = window.event.offsetY - document.body.scrollTop
}
}
// restore everything as before (called by onMouseUp)
function release() {
if (selectedObj) {
document.onmousemove = null
selectedObj = null
}
}
</script>
<body>
<h1>onMouseMove Event Handler</h1>
<img id="camap" src="d:/bw/n001387.jpg" style="left: 31px; top: 1px" />
<br />
<img id="ormap" src="d:/bw/n001387.jpg" style="left: 31px; top: 297px" />
<br />
<img id="wamap" src="d:/bw/n001387.jpg" style="left: 31px; top: 184px" />
<br />
</body>
</html>