0
我正在編寫一個Web應用程序,用戶可以通過用鼠標拖動div元素內的圖像來平移地圖。不幸的是,我需要它是跨瀏覽器,以支持IE 6-9,Firefox,Chrome和Safari。而且我被困在一個框架內,這對我可以用javascript做的限制,所以越簡單越好。下面的代碼(驚人)工作,直到我添加「!DOCTYPE html」。什麼是錯誤?你將如何調試?在HTML5中使用JavaScript移動元素
<!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>
就是這樣,謝謝! – David
解決方案,onmousemove中的更改: img.style.left =((window.event?window.event.x:event.clientX) - img.mouseX)+「px」; img.style.top =((window.event?window.event.y:event.clientY) - img.mouseY)+「px」; – David