Javascript/CSS : Cannot move background with positionBackground

标签 javascript html css animation

我想无限移动我的背景,为此我编写了以下代码:

    html, body {
    margin : 0;
    padding: 0;
    width: 100%;
    height: 100%;
    cursor: url('../assets/img/ship.cur'), auto;
    background-color : #000;
}

#background {
    position : absolute;
    background-image: url('../assets/img/littlestars.png');
    height : 720px;
    width : 1280px;
}

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <link rel="stylesheet" href="../style/home.css">
  <script language=javascript src="../js/navigate.js"> </script>
  <script language=javascript src="../js/background.js"> </script>
</head>
<body onLoad="onLoad(); loadBG();">
  <div id="background"> </div>

</body>
</html>

function loadBG() {
    window.setInterval(moveStars, 100);
}

function moveStars() {
    var bg = document.getElementById("background");
     bg.style.backgroundPosition += 10;
}

但它不起作用...如果我无法显示 backgroundPosition。

一些想法?这是创建 javascript 动画的好方法吗?谢谢。

最佳答案

backgroundPosition 是一个属性,以单位表示背景的 x、y 位置,而不是单个数字。

你需要做类似的事情:

var posx = 0;
function moveStars() {
    var bg = document.getElementById("background");
    posx+=10;
    bg.style.backgroundPosition = posx+"px 0";
}

关于Javascript/CSS : Cannot move background with positionBackground,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19054197/

相关文章:

javascript - 使用新的 proxyUrl 重试失败的页面

javascript - 强制从数据列表或等效项中选择(文本输入)

jquery - 在每个页面上包含 Bootstrap Navbar

javascript - 表单 onsubmit 不起作用

css - 如何使堆叠的 Font Awesome 图标与固定宽度的非堆叠图标具有相同的宽度?

javascript - 阻止 split 失去焦点

javascript - 动态添加的指令没有响应

javascript - 许多文本区域无法正常工作 - JQuery

jquery - 如何动画 "visibility: hidden"?

Javascript 注入(inject) - 更改文本字段大小