可以使用jQuery的动画来移动HTML背景吗?

时间:2015-02-16 09:19:28

标签: javascript jquery html css jquery-animate

在我的网页上,我使用HTML选择器设置了CSS背景图像。背景图像基本上类似于蓝图示意图背景。 (即蓝色背景上的白色网格。)

CSS:

html
{
    display: block;
    position: absolute;
    background: url(../assets/background.jpg) repeat;
    color: #FFF;
    margin: 0px;
    padding: 0px;
    border: none;
}

当最终用户点击按钮时,我希望上面提到的背景图像从屏幕向右上方向滑动,使页面看起来像是在大蓝图原理图上的不同区域。我正在使用jQuery,但我无法弄清楚如何从CSS访问背景图像。

JavaScript的:

$("#button").click(function()
{
    // Animate the webpage's background, causing it to move
    $("html /* Not sure what goes here */").animate({left: "-=10000px", top: "-=5000px"}, 1250);
});

我尝试在主体中使用与最终用户屏幕的宽度和高度相匹配的div,但在蓝图原理图像周围出现了一个粗的白色边框,所以我想我必须坚持添加图像CSS,在HTML选择器上。

我如何达到我想要的效果?

https://jsfiddle.net/zaevzm5p/

4 个答案:

答案 0 :(得分:6)

工作Fiddle

不要animate完整的HTML,因为它会为您的整个网站制作动画,因此我使用您想要的div创建了background,而不是设置{ {1}}的{​​1}}。

<强> HTML

background

<强> CSS

HTML

<强>的jQuery

<body>
    <div id="div1"></div>
    <button id="button">Click Me</button>
</body>

答案 1 :(得分:2)

我使用div而不是html本身,试试这个

solution 1

    $("#button").click(function () {
    // Animate the webpage's background, causing it to move
    $("#div1").animate({
        left: "-=10000px",
        top: "-=5000px"
    }, 1250);
});

答案 2 :(得分:1)

也可以通过CSS过渡来实现:

Fiddle Example

少JS,加上CSS

-webkit-transition: 1.25s ease-in-out;
-moz-transition: 1.25s ease-in-out;
-o-transition: 1.25s ease-in-out;
transition: 1.25s ease-in-out;

答案 3 :(得分:0)

你可以在无效的答案中创建一个div,只是为它的位置设置动画。

最好和最简单的解决方案是使用css3(只是谷歌)。

要提供原始问题的解决方案,您可以(如果浏览器支持),为背景位置设置动画,如下所示:

$("#button").click(function () {
    // Animate the webpage's background, causing it to move
    $("html /* Not sure what goes here */").animate({
        'background-position-x': "100px",
        'background-position-y': "100px"
    }, 1250);
});

但这是最佳做法。

Working fiddle