当用户单击以图像作为背景的链接时,我需要一个 onClick 事件来更改它的背景位置。这是链接:
<a href="#" id="favorite_1" class="favorite" onClick="favoriteBusiness(1);">Favorite</a>
已经在css中设置好了,有两种状态,regular和hover,hover移动了12px。
a.favorite {
width: 15px;
height: 12px;
background: url(img/icon-fav.png) no-repeat;
overflow: hidden;
position: absolute;
top: 0;
right: 0;
text-indent: -300px;
}
a.favorite:hover {
background-position: 0 -12px
}
当我点击一次图片时,我需要将背景位置设置为与悬停状态相同。
我就是这样做的,而且效果很好:
document.getElementById("favorite_1").style.backgroundPosition = "0 -12px";
但是当再次点击链接时,我需要它切换回正常的背景位置,但我无法让它工作。这是我正在尝试的功能,但它仅适用于将背景移动到“0 -12px”,而不是将其移回其原始位置。
function favoriteBusiness(id){
if(document.getElementById("favorite_1").style.backgroundPosition == "0 -12px")
document.getElementById("favorite_1").style.backgroundPosition = "";
else
document.getElementById("favorite_1").style.backgroundPosition = "0 -12px";
}
有人能给我指出正确的方向吗?
最佳答案
除非您进行计算,否则最好添加和删除包含新位置的类。这通常是操纵 CSS Sprite 所做的。
关于javascript - 使用 Javascript 设置图像的背景位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10195896/