我想创建一个300像素乘以300像素的div盒子,当用户将鼠标放在盒子上时,它会移动几个像素。唯一的问题是当div到达浏览器大小的末端时,我希望它开始向另一个方向移动,并且不会让窗口滚动。非常感谢任何帮助。
<div style="left:300px; top:300px; width:300px; height:300px; background:blue;>
</div>
这是 Oleg 的代码,我在 Firefox 中运行时遇到了问题,是我做错了什么吗?
<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>