自动精灵计算-CSS3或Jquery?

问题描述

| 我在图库中使用图片精灵。为了在正确的位置获得正确的背景图像,我使用以下命令:
<style>
#container div:nth-child(1){background-position:0 0}
#container div:nth-child(2){background-position:200px 0}
#container div:nth-child(3){background-position:400px 0}
#container div:nth-child(4){background-position:600px 0}
#container div:nth-child(5){background-position:800px 0}
#container div:nth-child(6){background-position:1000px 0}
</style>
当有很多div标签并且要添加的数字例如是73px而不是200时,对所有背景值进行计数是一种耗时的工作。它还会占用大量的CSS代码。 我可以使用CSS3以另一种方式获得相同的结果吗? 否则,我想知道是否有人可以查看我的jquery脚本,以查看是否可以通过更好的方式完成某些操作(该脚本有效):
<div id=\"container\">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
</div>

<script type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js\"></script>
<script>
$(function() {
$(\"#container div:first-child\").fadeIn(400,showNext);
});

function showNext() {
var test1 = $(this).index(),test2 = test1*200;

if (navigator.appName==\'Microsoft Internet Explorer\'){
$(this).css(\'backgroundPositionX\',-test2);
}
else{
$(this).css(\'backgroundPosition\',-test2);
}

$(this).next().fadeIn(400,showNext);
}
</script>
    

解决方法

我没有要处理的背景图像,但这是使用传递给CSS的函数修改元素高度的示例。您要做的就是将
height
属性换成
backgroundPosition
属性,然后将返回值切换为负数。 这应该大大减少您的代码。
$(function() {
    $(\"#container div\").css(\'height\',function(i,oldValue) {
        return (i+1)*200;
    }).fadeIn(400);
});
证明在摆弄。 如果您要修改多个CSS属性,则需要使用map或.CSS示例页面上概述的其他一些方法:http://api.jquery.com/css/ 哦,也请注意,切勿显式检测类似的浏览器。您想进行特征检测,因为我敢打赌您的代码破坏了IE9,假设IE9现在处理背景定位的方式与IE8不同。 http://www.jibbering.com/faq/notes/detect-browser/