【问题标题】:animating multiple background positions using jQuery使用 jQuery 为多个背景位置设置动画
【发布时间】:2012-10-30 15:59:46
【问题描述】:

我正在为我的 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 处理多个背景位置属性?!

【问题讨论】:

    标签: jquery jquery-animate background-position


    【解决方案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 来伪造它,然后调整它们的大小。

    【讨论】:

    • 删除分号会破坏整个事情并使用backgournd-positiond 而不是-x-y 也不起作用。没有动画这个代码完美地工作:background-position','-150px 0px, 255px 0px 但是当我在animate 函数中使用它时它什么都不做..
    • 经过一番研究,似乎 jQuery 无法真正访问必要的属性来允许“动画”背景图像属性。不过我会继续寻找。
    • 错误。 jquery 可以为 ONE 背景图片的位置设置动画!示例:$('#element').animate({'background-position-x': '+=400px'}, 400); 我不知道如何在同一个元素上为两个背景图像设置动画...
    【解决方案2】:

    只需使用 'background-position' : 'value px value px''left top' 或任何适合您的方式。

    【讨论】:

    • 你能举例说明如何使用这些属性吗?这将对不熟悉 jQuery 的人有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-14
    • 1970-01-01
    • 2011-07-07
    • 2011-03-01
    相关资源
    最近更新 更多