App下載

css輪播圖如何實(shí)現(xiàn)?

猿友 2021-04-20 18:03:48 瀏覽數(shù) (4400)
反饋

在往期文章小編介紹過 JS 如何實(shí)現(xiàn)輪播圖。那么這篇文章我們來介紹另一種方法:CSS 輪播圖如何實(shí)現(xiàn)。

實(shí)現(xiàn)效果

CSS實(shí)現(xiàn)輪播圖效果

實(shí)現(xiàn)思路

用 CSS 實(shí)現(xiàn)圖片輪播主要是用到 CSS3 ?animation? 屬性和 ?@keyframes?。首先將要進(jìn)行輪播的圖片放入一個 div 內(nèi),此 div 的寬度設(shè)置為多張圖片寬度的總和。在此 div 外再設(shè)一個 div,將此 div 的寬高設(shè)置為一張圖片的寬高,并將 overflow 設(shè)置為 ?hidden?。

隨后設(shè)置動畫屬性,此處輪播總共有四張圖片,所以添加四個動畫階段,0%-20% 是第一張圖片的動畫階段,20%-25% 是停留階段,以下以此類推。

具體代碼

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>CSS如何實(shí)現(xiàn)輪播圖 - 編程獅(w3cschool.cn)</title>
	<style type="text/css">
		div{
			width: 300px;
			height: 168px;
			overflow: hidden;
		}
		#lunbotu{
			width: 1200px;
			animation: lunbotu 6s linear  ;/*lunbotu為動畫名稱,此動畫持續(xù)6s,速度相同*/
		}
		#lunbotu>img{
			float: left;
			width: 300px;
		}
		@-webkit-keyframes lunbotu{
		0%,20%{
			margin-left: 0;
		}
		25%,45%{
			margin-left: -300px;
		}
		50%,70%{
			margin-left: -600px;
		}
		75%,100%{
			margin-left: -900px;
		}
		}

	</style>
</head>
<body>
	<div>
		<div id="lunbotu">
			<img src="https://atts.w3cschool.cn/attachments/cover/cover_css_txy.jpeg?t=1599114933" alt="">
			<img src="https://atts.w3cschool.cn/attachments/cover/cover_my_qianduan.jpeg?t=1587609360" alt="">
			<img src="https://atts.w3cschool.cn/attachments/cover/cover_css_job_my.png?t=1607312870" alt="">
			<img src="https://atts.w3cschool.cn/attachments/cover/cover_qianduan_rygh.png?t=1609142979" alt="">
		</div>
	</div>
</body>
</html>

以上就是 CSS 輪播圖如何實(shí)現(xiàn)的全部內(nèi)容。更多 CSS 學(xué)習(xí)請關(guān)注 w3cschool 官網(wǎng)


CSS

0 人點(diǎn)贊