問題:輪播圖中,在大屏幕和較大屏幕上(桌面端)要求圖片的高度不隨屏幕大小而改變,在較小屏幕上(移動設備)圖片的大小隨屏幕的大小而自適應
解決思路:設置兩個同級的a標簽,給第一個a標簽設置背景圖片,其background-size設置為cover,並給a標簽添加類:class=''hidden-xs hidden-sm'',讓其在小屏幕上隱藏;
第二個a標簽添加類:class=''hidden-lg hidden-md'',讓其在小屏幕上顯示,在大屏幕上隱藏,並給a標簽下的img標簽設置樣式,width:100%,display:block;讓其寬高隨屏幕大小自動改變。
源代碼:
html部分:
1 <!--輪播圖部分--> 2 <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> 3 <!-- Indicators --> 4 <ol class="carousel-indicators"> 5 <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li> 6 <li data-target="#carousel-example-generic" data-slide-to="1"></li> 7 <li data-target="#carousel-example-generic" data-slide-to="2"></li> 8 <li data-target="#carousel-example-generic" data-slide-to="3"></li> 9 </ol> 10 11 <!-- Wrapper for slides --> 12 <div class="carousel-inner rotate" role="listbox"> 13 <div class="item active"> 14 <a href="#" class="large_screen hidden-sm hidden-xs"></a> 15 <a href="#" class="mobile_a hidden-lg hidden-md"><img src="images/slide_01_640x340.jpg" alt=""></a> 16 </div> 17 <div class="item"> 18 <a href="#" class="large_screen hidden-sm hidden-xs"></a> 19 <a href="#" class="mobile_a hidden-lg hidden-md"><img src="images/slide_02_640x340.jpg" alt=""></a> 20 </div> 21 <div class="item"> 22 <a href="#" class="large_screen hidden-sm hidden-xs"></a> 23 <a href="#" class="mobile_a hidden-lg hidden-md"><img src="images/slide_03_640x340.jpg" alt=""></a> 24 </div> 25 <div class="item"> 26 <a href="#" class="large_screen hidden-sm hidden-xs"></a> 27 <a href="#" class="mobile_a hidden-lg hidden-md"><img src="images/slide_04_640x340.jpg" alt=""></a> 28 </div> 29 </div> 30 31 <!-- Controls --> 32 <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev"> 33 <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> 34 <span class="sr-only">Previous</span> 35 </a> 36 <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next"> 37 <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> 38 <span class="sr-only">Next</span> 39 </a> 40 </div>
css部分:
1 /*輪播圖樣式*/ 2 .rotate{ 3 margin-top: 0; 4 } 5 .rotate .item a.large_screen{ 6 display:block; 7 height:410px; 8 background-size:cover; 9 background-repeat: no-repeat; 10 background-position: center; 11 } 12 .rotate .item:first-child a.large_screen{ 13 background-image: url("../images/slide_01_2000x410.jpg"); 14 } 15 .rotate .item:nth-child(2) a.large_screen{ 16 background-image: url("../images/slide_02_2000x410.jpg"); 17 } 18 .rotate .item:nth-child(3) a.large_screen{ 19 background-image: url("../images/slide_03_2000x410.jpg"); 20 } 21 .rotate .item:last-child a.large_screen{ 22 background-image: url("../images/slide_04_2000x410.jpg"); 23 } 24 .rotate .item a.mobile_a{ 25 display: block; 26 width:100%; 27 } 28 .rotate .item a.mobile_a img{ 29 display: block; 30 width:100%; 31 }