我正在尝试重新创建《太空侵略者》。但仅限于 Javascript,没有 jQuery 等。 现在我为火箭打造一个“家庭”:
var image = document.createElement('img');
image.setAttribute('src', 'Rakete.gif');
image.setAttribute("style",
"position:absolute; left:" + x2 + "px; top:bottom; bottom:55px;");
我用它来将它添加到正文中:
document.body.appendChild(image);
现在我的问题是:如何将每秒的 bottom:55px;
替换为 +1px
?
我把这一切都放在一个带有计时器的函数中。我的问题只是我不知道如何替换每个子元素的bottom
。我需要增加每个 child 的bottom
。
最佳答案
首先为所有此类图像设置一个类会更容易:
image.setAttribute("class", "rocket");
您的计时器需要如下所示:
var rockets = document.getElementsByClassName("rocket"); // Gets all elements with class “rocket”
setInterval(function(){
var maximumHeight = window.innerHeight; // maximum value for bottom before element gets removed
for(var i = 0; i < rockets.length; i++){ // Now, iterate over every element with class “rocket” with a for loop
rockets[i].style.bottom = (Number( // Convert the following into a number
rockets[i] // the element
.style // its CSS data
.bottom // the bottom property
.match(/[\+\-]?(?:\d*\.?\d+)/) // the number part of it (in any format)
) + 1) // increment!
+ "px"; // plus the string 'px'
if(Number(rockets[i].style.bottom.match(/[\+\-]?(?:\d*\.?\d+)/)) > maximumHeight){
// If maximum height is exceeded
rockets[i].remove(); // Remove that child
}
}
},
1000); // 1000ms = 1s
或总结:
var rockets = document.getElementsByClassName("rocket");
setInterval(function(){
var maximumHeight = window.innerHeight;
for(var i = 0; i < rockets.length; i++){
rockets[i].style.bottom =
(Number(rockets[i].style.bottom.match(/[\+\-]?(?:\d*\.?\d+)/)) + 1) + "px";
if(Number(rockets[i].style.bottom.match(/[\+\-]?(?:\d*\.?\d+)/)) > maximumHeight){
rockets[i].remove();
}
}
}, 1000);
这只是每秒操作 CSS 数据。
只有一件事需要注意:... .match(/…/)
将返回 Array
如果找到号码或 null
如果没有找到任何内容(例如,如果 bottom
属性尚未设置并且为空或无效)。这对于Number()
来说并不重要。 ! Number(['42'])
仍然返回数字 42
和Number(null)
安全返回0
.
如果您确实有自己的备用号码(例如),您可以使用 ||
或运算符:
rockets[i].style.bottom =
(Number(rockets[i].style.bottom.match(/[\+\-]?(?:\d*\.?\d+)/) || 55) + 1) + "px";
<小时/>
ECMAScript 2015+ 方法
const rockets = document.getElementsByClassName("rocket"),
numberPattern = /[\+\-]?(?:\d*\.?\d+)/;
setInterval(() => {
const maximumHeight = window.innerHeight;
Array.from(rockets).forEach((rocket) => {
rocket.style.bottom = (Number(elem.style.bottom.match(numberPattern)) + 1) + "px";
if(Number(rocket.style.bottom.match(numberPattern)) > maximumHeight){
rocket.remove();
}
});
}, 1000);
关于javascript - 使用计时器将父子图片移动 1px,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29953271/