使用jQuery动画化多个背景位置

时间:2012-10-30 15:59:47

标签: jquery jquery-animate background-position

我正在为我的wordpress主题的侧边栏小部件创建一个切换下拉效果。

小部件内的

h2标签有两个背景图像,背景位置不同。

这个背景的CSS就像这样:

background-image: url(images/h2bg.png), url(images/button.png);
background-position: center left, bottom right;
background-repeat: no-repeat,no-repeat;

我想要做的是在用户点击h2元素时为元素框中的第一个背景(h2bg.png)设置动画,然后将第二个背景图像的位置更改为top left。 (这是一个很小的精灵图像)

我的jQuery脚本是这样的:(你不需要经历它)

$(document).ready(function() {
    $('#sidebar div.widget').each(function(i) {
        height = $(this).css('height');
        $(this).attr('data-height',height);
        $(this).attr('data-animate','ON');
    });
    $('.widget h2').click(function() {
        if ($(this).parent('div.widget').attr('data-animate') == 'OFF') {
            $(this).parent('div.widget').attr('data-animate','ON');
            height = $(this).parent('div.widget').attr('data-height');
            $(this).parent('div.widget').animate({
                height: height
            },500);
            $(this).animate({
                'background-position-x': '0%, 100%'
            },500,function() {
                $(this).css('background-position-y','50%, 100%');
            });
        } else {
            $(this).parent('div.widget').attr('data-animate','OFF');
            $(this).parent('div.widget').animate({
                height: '29px'
            },500);
            $(this).animate({
                'background-position-x': '-100%, 100%'
            },500,function() {
                $(this).css('background-position-y','50%, 0%');
            });
        }
    });
});

长话短说..我注意到javascript会返回background-position-xbackground-position-y作为percenatges,其间有分号。

所以我在动画中使用百分比,它对一个背景图像工作正常。但是当谈到多个背景时,它不起作用!我用分号试了......没有分号和像素值,但没有运气!

如何使用jQuery处理多个背景位置属性?!

2 个答案:

答案 0 :(得分:1)

您可能需要重新定义.css / .animate方法中的图片网址。

'background-image' : 'url("image1.png"), url("image2.png")',
'background-position' : 'right 50px left 50px' (or whatever)

CSS使用image-url声明的序列来确定哪些属性适用于哪个图像,因此可能只是浏览器没有引用点的情况(由于样式是内联而不是在样式表)。

另外,坚持'背景位置'声明。不确定background-position-x,background-position-y是否适用于多个图像。

更新

jQuery无法为背景图像设置动画。为了获得相同的效果,你必须通过在目标元素下使用堆叠的div来伪造并重新调整它们。

答案 1 :(得分:0)

只需使用'background-position' : 'value px value px''left top'或其他适合您的工作。