在JavaScript中制作页面漂浮广告,鼠标停在图片上停止,离开移动
时间: 2024-06-11 10:10:22 浏览: 13
以下是一个简单的示例,漂浮广告为一个图片,当鼠标停在图片上时,广告停止漂浮,离开时继续漂浮:
HTML代码:
```
<div id="floatAd">
<img src="广告图片地址" alt="广告">
</div>
```
CSS代码:
```
#floatAd {
position: fixed;
bottom: 0;
right: 0;
}
#floatAd img {
width: 200px;
height: 200px;
cursor: pointer;
}
```
JavaScript代码:
```
var floatAd = document.getElementById('floatAd');
var adImg = floatAd.getElementsByTagName('img')[0];
var dx = 2; // 漂浮距离
var dy = 2;
var floatInterval = setInterval(function() {
var x = parseFloat(floatAd.style.right);
var y = parseFloat(floatAd.style.bottom);
if (x <= 0 || x >= (window.innerWidth - adImg.width)) {
dx = -dx;
}
if (y <= 0 || y >= (window.innerHeight - adImg.height)) {
dy = -dy;
}
floatAd.style.right = (x + dx) + 'px';
floatAd.style.bottom = (y + dy) + 'px';
}, 10);
adImg.addEventListener('mouseover', function() {
clearInterval(floatInterval);
});
adImg.addEventListener('mouseout', function() {
floatInterval = setInterval(function() {
var x = parseFloat(floatAd.style.right);
var y = parseFloat(floatAd.style.bottom);
if (x <= 0 || x >= (window.innerWidth - adImg.width)) {
dx = -dx;
}
if (y <= 0 || y >= (window.innerHeight - adImg.height)) {
dy = -dy;
}
floatAd.style.right = (x + dx) + 'px';
floatAd.style.bottom = (y + dy) + 'px';
}, 10);
});
```
解释:
- 通过`getElementById`方法获取漂浮广告节点和图片节点;
- 定义漂浮距离`dx`和`dy`,并设置漂浮间隔为10毫秒;
- 使用`setInterval`方法循环移动广告,当广告到达窗口边缘时改变漂浮方向;
- 当鼠标停在图片上时,使用`clearInterval`方法停止漂浮;
- 当鼠标离开图片时,重新开始漂浮。
注意事项:
- 漂浮广告的位置使用`position: fixed`实现,需要在CSS中设置`bottom`和`right`属性;
- 图片节点需要设置`cursor: pointer`属性,以便在鼠标停在图片上时改变鼠标指针形状;
- 可以根据实际需求调整漂浮距离和漂浮间隔。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)