0

我为我的画廊使用图像精灵。为了在正确的位置获得正确的背景图像,我使用了这个:

<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>
4

1 回答 1

1

我没有要处理的背景图像,但这里有一个使用传递给 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/

于 2011-05-23T12:49:39.550 回答