我正在尝试创建一个 300 像素 x 300 像素的 div 框,当用户将鼠标放在框上时,它会移动几个像素。唯一的事情是当 div 达到浏览器大小的末尾时,我希望它开始以另一种方式移动而不是使窗口滚动。任何帮助将不胜感激。
<div style="left:300px; top:300px; width:300px; height:300px; background:blue;>
</div>
这是我在 Firefox 中运行时遇到问题的 oleg 代码,我做错了吗?
<html>
<head>
<script>
window.onload = function () {
var speed = 10, // the box will move by 10 pixels on every step
direction = 1, // 1 = move right; -1 = move left
boxElement = document.getElementById('theIdOfTheBox');
if (boxElement) {
boxElement.addEventListener('mouseover', function () {
// Calculate and store some of the box coordinates:
var boxLeftPos = boxElement.offsetLeft,
boxRightPos = boxLeftPos + boxElement.offsetWidth;
// When right side of the box goes too far - change direction:
if (boxRightPos > document.body.offsetWidth) {
direction = -1;
}
// When left side of the box goes too far - change direction:
if (boxLeftPos < 0) {
direction = 1;
}
// Recalculate position:
boxElement.style.left = (boxLeftPos + speed * direction) + 'px';
});
}
};
</script>
<style>
#theIdOfTheBox {
position: absolute;
left:100px;
top:100px;
width:300px;
height:300px;
background:blue;
}
</style>
</head>
<body>
<div id="theIdOfTheBox">box</div>
</body>
</html>