1

我正在为我的 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作为百分比,中间有分号。

所以我在动画中使用了百分比,它适用于一张背景图片。但是当涉及到多个背景时,它就不起作用了!我用分号试过..​​....没有分号和像素值,但没有运气!

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

4

2 回答 2

1

您可能需要在 .css/.animate 方法中重新定义图像 URL。

'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来伪造它并调整它们的大小。

于 2012-10-31T18:20:14.310 回答
0

只需使用'background-position' : 'value px value px''left top'任何适合你的东西。

于 2012-10-31T18:09:42.277 回答