css 雪碧圖 及jquery定位代碼


無意間發現了一個很神奇的事情,就是

 

鼠標懸停在圖片上方會切換,起初以為圖標是單獨插入的。但發現居然是一張完整的圖片。

一萬只草泥馬在心中奔騰。這是怎么實現的?

后來詢問得知,這是css精靈技術(sprite) 也叫雪碧圖。

 

CSS知識點:
    • background-image
    • backgorund-position
  • 特點:
    1. 相對於當個小圖標,它節省文件體積和服務請求次數。將所有零碎的網頁背景圖片整合到一起,這樣做可以有效的減少http對圖片的請求次數,而不需要加載多次加載零碎的背景圖片,所以合理的利用好它可以有效的提高網頁的加載速度。
    2. 一般情況下,你需要保存為PNG-24的文件格式。
    3. 可以設計出豐富多彩的顏色體表。
  • 難點:
    1. 你需預先確定每個小圖標的大小
    2. 注意小圖標與小圖標之間的距離
    3. 細心、耐心

 

於是,我百度之后。我決定玩一玩

HTML結構
<
ul> <li><a href="#"></a></li> <li><a href="#"></a></li> <li><a href="#"></a></li> <li><a href="#"></a></li> <li><a href="#"></a></li> <li><a href="#"></a></li> </ul>

css

<style>
        ul{
            position: absolute;
            top: 50px;
            height:31px;
            
        }
        li{
            list-style: none;
            float:left;
            width:30px;
            height: 31px;
            margin-right: 30px;
        }
        a{
            width:30px;
            height: 31px;
            display: block;
            background: url(images/social-media.png) no-repeat;
            background-position: 8px 0px;
            
        }
    </style>

 

用css來定位坐標的話,十分浪費時間,於是可以用jquery統一設置坐標(ss雪碧圖的定位參數按實際需求)

<script>
    $(function() {
        var index;
        var icorW;
        $("ul>li").each(function(index) {
            index = $(this).index();//獲取對象的索引值
            icorW = $(this).width()+2;//獲取對象寬度
            var _this = $(this);
            $(_this).children().attr("style","background-position:"+(8-(index *icorW))+"px 0px");//先眾神歸位
            
            $(_this).hover(function () {
                $(_this).children().attr("style","background-position:"+(8-(index *icorW))+"px 103%");

                $("span").html(index);//測試索引數值

            },function(){
                $(_this).children().attr("style","background-position:"+(8-(index *icorW))+"px 0px");
            })
            
        })
    
    })
    </script>

 

參考

月上西樓

 http://blog.163.com/zhangmihuo_2007/blog/static/270110752015011391211/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM