在悬停或活动时更改背景位置的正确方法是什么

时间:2011-12-11 10:38:10

标签: html css background background-image sprite

如果我有这样一个按钮:

a#settingsCloseButton {
        background: url("img/my_account_sprite.png") no-repeat scroll 0 -155px transparent;
        display: block;
        height: 14px;
        text-indent: -3000px;
        width: 14px;
    }

我用来写:hover和:这样活跃:

a#settingsCloseButton:hover {
        background: url("img/my_account_sprite.png") no-repeat scroll -14px -155px transparent;
    }

a#settingsCloseButton:active {
        background: url("img/my_account_sprite.png") no-repeat scroll -28px -155px transparent;
    }

我的问题是:如果我只用 background-poistion 这样写它会让我更好地加载性能:

a#settingsCloseButton:hover {
        background-posiiton: -14px -155px;
    }

a#settingsCloseButton:active {
        background-posiiton: -28px -155px;

    }

复制整个背景属性比较容易,因为我可以分辨出图像的来源(如第一个例子)。但这是否意味着重新加载它?一个选项加载速度快于另一个选项还是它们都相同?

感谢, 阿隆

2 个答案:

答案 0 :(得分:3)

没有因额外负载或类似情况而导致的性能损失。一旦浏览器第一次加载图像,它就会将图像存储在内存中,并且每次在样式表中引用时都不需要再加载它。

仅设置background-position属性就可以清楚地表明所有真正改变的是背景位置。如果它们不会在:hover:active状态中发生变化,则无需重复其余值(图像,重复,附件)。

答案 1 :(得分:1)

老实说,我认为它不会影响性能,因为图像在第一次加载时已经被缓存了。

但是,同样 - 我没有看到两次设置“背景”的用法。 我会做的

a#settingsCloseButton{
    background-image: url('img/my_account_sprite.png');
    background-repeat: no-repeat;
    background-position: 0px 0px;
}

a#settingsCloseButton:hover{
   background-position: -20px -20px;
}

晒。

相关问题