以下是一个简单的CSS实现广告自动轮播的例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Auto-Playing Ads</title>
<style>
.ads {
display: flex;
overflow: hidden;
width: 300px;
height: 200px;
}
.ads-container {
display: flex;
transition: transform 0.5s ease;
}
.ads-slide {
flex: 1 0 auto;
display: flex;
align-items: center;
justify-content: center;
background-color: #f2f2f2;
position: relative;
}
.ads-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background-color: #ccc;
margin: 0 4px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.ads-dot.active {
background-color: #000;
}
</style>
</head>
<body>
<div class="ads">
<div class="ads-container">
<div class="ads-slide"><img src="ad1.jpg" alt="Ad 1"></div>
<div class="ads-slide"><img src="ad2.jpg" alt="Ad 2"></div>
<div class="ads-slide"><img src="ad3.jpg" alt="Ad 3"></div>
</div>
</div>
<script>
const adsContainer = document.querySelector('.ads-container');
const adsDots = document.querySelectorAll('.ads-dot');
let currentIndex = 0;
function showSlide(index) {
const translateX = `-${index * 100}%`;
adsContainer.style.transform = `translateX(${translateX})`;
}
function updateDots(index) {
adsDots.forEach((dot, dotIndex) => {
dot.classList.toggle('active', dotIndex === index);
});
}
function autoPlay() {
currentIndex = (currentIndex + 1) % adsDots.length;
showSlide(currentIndex);
updateDots(currentIndex);
}
setInterval(autoPlay, 3000);
</script>
</body>
</html>
这段代码包含了一个简单的自动轮播广告的实现。它使用了CSS Flexbox来布局广告容器和广告元素,并使用JavaScript来控制自动播放。setInterval
函数用于每隔3秒自动切换到下一个广告。这个例子假设你有三张广告图片(ad1.jpg, ad2.jpg, ad3.jpg)供轮播展示。