jQuery实现图标特效(精灵图)

it2023-07-29  73

常见的特效,用到了CSS的精灵图,jQuery代码稍微复杂点,笔者会讲解重点。 PS:为啥笔者的图标缺三个?因为随手百度的精灵图只有五个图标,也懒得换,大家找个多一点的就行了。

效果图

<style> * { padding: 0; margin: 0; } ul { width: 400px; height: 300px; border: 1px solid #000; margin: 150px auto; list-style: none; } ul > li { float: left; width: 80px; line-height: 100px; padding-left: 20px; position: relative; overflow: hidden; } ul > li:nth-child(-n+4) { margin-top: 50px; } ul > li > span { display: inline-block; width: 30px; height: 30px; background: url("img/jlt/精灵图.png") no-repeat 0 0; border-radius: 50%; position: absolute; top: 5%; } </style> <body> <ul> <li><span></span>图标</li> <li><span></span>图标</li> <li><span></span>图标</li> <li><span></span>图标</li> <li><span></span>图标</li> <li><span></span>图标</li> <li><span></span>图标</li> <li><span></span>图标</li> </ul> </body>

ul > li:nth-child(-n+4) 这句话的意思是ul 的子元素li(不包括后代的li)中的前四个。

<script> $(function () { var lis = $('li'); lis.each(function (index, ele) { var url = 'url("img/jlt/精灵图.png") no-repeat 0 ' + (index * -52) + 'px'; $(this).children('span').css('background', url); console.log(url); }) lis.mouseenter(function () { //animate无法修改颜色 $(this).children('span').animate({ top: '-50%', }, 300, function () { $(this).css('top', '50%'); }) $(this).children('span').animate({ top: '5%' }, 300, function () { $(this).stop(true); }) }) }); </script>

第一个each循环就是设置精灵图的位置,让他露出不同的图标,这也是精灵图的大概原理。剩余部分基本就是在讲animate()方法,笔者之前的文章有详细讲到。 jQuery中的animate()方法是无法更改颜色的。

如果有疑问,欢迎各位留言或者私信,觉得不错的就点个赞吧~!

最新回复(0)