我正在编写一个 Web 应用程序,用户可以通过用鼠标在 div 元素内拖动图像来平移地图。不幸的是,我需要它是跨浏览器的,以支持 IE 6-9、Firefox、Chrome 和 Safari。而且我被困在一个框架中,这个框架限制了我可以用 javascript 做什么,所以越简单越好。下面的代码(惊人地)有效,直到我添加了“!DOCTYPE html”。有什么错误?你将如何调试这个?
<!DOCTYPE html>
<html><head></head><body>
<style>
p{ width: 400px; background-color: gold;}
#caption {text-align: center; font-weight: bold;}
div div {
width:400px; height: 140px;
border: 1px solid green;
background-color: lightgreen;
display: block;
position: relative;
}
div div:hover {border-color: red;}
div > .img {
width: 200px; height: 100px; top: 10px; left: 20px;
position: absolute;
border: 2px solid black;
background-image: url('http://boallen.com/assets/images/randbitmap_true.png');
}
div > .img:hover {cursor: pointer; background-color: lightgray;}
</style>
<div>
<div>p
<span class="img" id="friend">bad ie</span>
</div>
<div id="thediv">Mouse in here and click<br></div>
</div>
<script>
var el = document.getElementById("thediv");
var img = document.getElementById('friend');
img.onmousedown = function (event) {
img.moving=true;
img.mouseX=(window.event ? window.event.x: event.clientX) - img.offsetLeft;
img.mouseY=(window.event ? window.event.y: event.clientY) - img.offsetTop;
el.innerHTML += 'Mouse DOWN ';
}
img.onmousemove = function (event) {
if(!img.moving) return;
img.style.left=(window.event ? window.event.x: event.clientX) - img.mouseX;
img.style.top=(window.event ? window.event.y: event.clientY) - img.mouseY;
stat.innerHTML += "M-M ";
}
img.onmouseup = function (event) {
this.moving = false;
el.innerHTML += 'Mouse released ';
}
</script>
</body>
</html>
(在 IE9、Firefox 和 Chrome 上使用http://htmledit.squarefree.com/测试)