使用JavaScript中的DOM编写 制作页面中的浮动广告效果,当鼠标指针悬浮在广告图片上时,广告图片停止移动,当鼠标指针移开时,广告图片继续浮动移动
时间: 2024-03-25 11:38:30 浏览: 19
好的,以下是一种使用JavaScript中的DOM实现浮动广告效果的代码:
HTML部分:
```html
<div id="ad-container">
<img id="ad-img" src="广告图片链接" alt="广告图片">
</div>
```
CSS部分:
```css
#ad-container {
position: fixed;
top: 100px;
left: 50%;
transform: translateX(-50%);
width: 200px;
height: 200px;
overflow: hidden;
}
#ad-img {
position: absolute;
width: 100%;
height: 100%;
cursor: pointer;
}
```
JavaScript部分:
```javascript
const adContainer = document.getElementById('ad-container');
const adImg = document.getElementById('ad-img');
let isHovering = false;
adContainer.addEventListener('mouseover', () => {
isHovering = true;
});
adContainer.addEventListener('mouseout', () => {
isHovering = false;
});
function animate() {
if (!isHovering) {
const x = parseFloat(adImg.style.left) || 0;
const y = parseFloat(adImg.style.top) || 0;
adImg.style.left = x + 1 + 'px';
adImg.style.top = y + 1 + 'px';
}
requestAnimationFrame(animate);
}
animate();
```
这段代码首先获取了广告容器和广告图片的 DOM 元素,接着定义了一个 `isHovering` 变量来判断是否鼠标悬停在广告图片上。然后,添加了 `mouseover` 和 `mouseout` 事件监听器,当鼠标指针悬浮在广告图片上时,将 `isHovering` 标记为 `true`,当鼠标指针离开广告图片时,将 `isHovering` 标记为 `false`。最后,定义了一个 `animate` 函数来改变广告图片的位置,如果 `isHovering` 为 `false`,则每次将广告图片的位置向右下方移动一像素,并使用 `requestAnimationFrame` 来实现动画效果。