Home >Web Front-end >HTML Tutorial >CSS Sprite (JS)_html/css_WEB-ITnose

CSS Sprite (JS)_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:52:35938browse

HTML

 1 <body> 2     <!-- ul.sprite>li*5>s.s-icon+a{CSS Sprite} --> 3     <!-- 以上是Sublime Text快速拼写 --> 4     <ul class="sprite"> 5         <li><s class="s-icon"></s><a href="">CSS Sprite</a></li> 6         <li><s class="s-icon"></s><a href="">CSS Sprite</a></li> 7         <li><s class="s-icon"></s><a href="">CSS Sprite</a></li> 8         <li><s class="s-icon"></s><a href="">CSS Sprite</a></li> 9         <li><s class="s-icon"></s><a href="">CSS Sprite</a></li>10         <div class="clear"></div>11     </ul>12 </body>

CSS

 1 <style> 2     body { background-color: #fc0; color:#333;} 3     * {margin:0; padding:0;} 4     ul,li {list-style: none;} 5     a { color:#f00; font-weight: bold; text-decoration: none;} 6     .sprite {margin:0 auto; width:1000px; padding-top: 50px;} 7     .sprite li {float:left; margin-left: 50px; text-align: center; cursor:pointer; } 8     .sprite li s { display: block; width:132px; height:112px; background:url(all.png) no-repeat; } 9     .clear { clear:both;}10 </style>

JS

 1 <script src="http://code.jquery.com/jquery-latest.js"></script> 2     <script> 3     $(function () { 4         var iconH = $(".sprite").find("s").height(), 5             //找出存放图片的容器的高度; 6             triggerLi = $(".sprite").children("li"); 7             //找出每一个li,放到一个数组中; 8         //console.log(iconH); 9         //在控制台打印出容器的高度;10         triggerLi.each(function () {11         //遍历数组中的每一个li12             var $this = $(this),13                 //声明变量赋值当前的li;14                 $index = $this.index();15                 //声明变量保存当前li的index值;16             //console.log($index);17             //在控制台打印出每一个li的index值;18             //console.log(iconH*$index);19             //得出每一个图片对应的position值;20             $this.children("s").css("background-position","0 -"+iconH*$index+"px");21             //利用js遍历出每一个s标签的背景图片;22             $this.hover(function() {23                 //鼠标移入24                 $this.children("s").css("background-position","-132px -"+iconH*$index+"px");25             }, function() {26                 //鼠标移出27                 $this.children("s").css("background-position","0 -"+iconH*$index+"px");28             });29         })30     })31     </script>

IMG (right click to save, rename all.png)

SHOW

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn