广告图片在页面中自由浮动,碰到浏览器边界会反弹回来,请使用html+css+js实现效果
时间: 2024-03-06 07:46:32 浏览: 20
好的,可以使用以下代码实现:
HTML代码:
```html
<div class="ad-container">
<img class="ad-image" src="your-image-url" alt="advertisement">
</div>
```
CSS代码:
```css
.ad-container {
position: relative;
width: 300px; /* 设置广告容器的宽度 */
height: 250px; /* 设置广告容器的高度 */
}
.ad-image {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: none;
}
```
JavaScript代码:
```javascript
const adContainer = document.querySelector('.ad-container');
const adImage = document.querySelector('.ad-image');
const containerWidth = adContainer.offsetWidth;
const containerHeight = adContainer.offsetHeight;
const imageWidth = adImage.offsetWidth;
const imageHeight = adImage.offsetHeight;
const speedX = 3; // 设置反弹速度,可以根据需要调整
const speedY = 3; // 设置反弹速度,可以根据需要调整
let posX = 0;
let posY = 0;
let directionX = 1;
let directionY = 1;
function move() {
posX += speedX * directionX;
posY += speedY * directionY;
if (posX + imageWidth > containerWidth) {
directionX = -1;
}
if (posX < 0) {
directionX = 1;
}
if (posY + imageHeight > containerHeight) {
directionY = -1;
}
if (posY < 0) {
directionY = 1;
}
adImage.style.transform = `translate(${posX}px, ${posY}px)`;
requestAnimationFrame(move);
}
move();
```
这段代码实现了一个广告图片在容器内自由浮动,并且碰到容器边界会反弹回来的效果。通过JavaScript代码实现了定时更新图片位置和反弹方向的功能,使用requestAnimationFrame方法可以让动画更加流畅。