首页 > 解决方案 > 我试图通过单击具有移动现有元素位置的按钮来创建元素,但它不起作用

问题描述

var arrow = document.getElementById("arrow");
function shot() {
var arrows = document.createElement("div");
document.body.appendChild(arrows);
arrows.style.backgroundColor = "black";
arrows.style.height = "80" + "px";
arrows.style.width = "3" + "px";
var arrowX = parseInt(document.arrow.style.left);
var arrowY = parseInt(document.arrow.style.top);
document.arrows.style.left = arrowX + "px"; 
document.arrows.style.top = arrowY + "px";
};

当我运行它并单击运行功能镜头的按钮时,它说它无法读取未定义的属性“样式”。它还会在没有任何位置定义的情况下在它会产生的位置上产生一个新元素。是的,我的身份证是正确的。

html:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div id="arrow"><div>
<button id="button" onclick="shot();"> Shot! </button>
</body>
</html>

CSS:

#arrow {
background-color: black;
height: 80px;
width: 1.5px;
position: relative;
left: 0px;
top: 0px;
}

这是您不需要的完整项目JS。它不完整。有更快的按钮,但它不起作用,我知道为什么。应该是射箭游戏

var arrow = document.getElementById("arrow");
var arrowPos = -50;
var speed = 1000;
var speed2 = speed/100;
function arrow_move_right() {

arrowPos += 1;
arrow.style.left = arrowPos + "px";
if (arrowPos >= 280) {
    return arrow_move_left()
}
else {
setTimeout(arrow_move_right, speed2);
};
};
function arrow_move_left() {
arrow = document.getElementById("arrow");
arrowPos -= 1;
arrow.style.left = arrowPos + "px";
if (arrowPos <= -50) {
    return arrow_move_right()
}
setTimeout(arrow_move_left, speed2);
};
function faster() {
speed -= 100;
alert(speed)
}

function shot() {
var arrows = document.createElement("div");
document.body.appendChild(arrows);
arrows.style.backgroundColor = "black";
arrows.style.height = "80" + "px";
arrows.style.width = "1.5" + "px";
var arrowX = parseInt(arrow.style.left);
var arrowY = parseInt(arrow.style.top);
alert(arrowX);
alert(arrowY);
// arrows.style.left = arrowX; 
// arrows.style.top = arrowY;
arrows.style.pos = "relative";
arrows.style.top = -50 + "px";
};

标签: javascriptpositioningcreateelement

解决方案


希望这就是你要找的!

var arrow = document.getElementById("arrow");
function shot() {
    var arrows = document.createElement("div");
    document.body.appendChild(arrows);
    arrows.style.backgroundColor = "blue";
    arrows.style.height = "80px";
    arrows.style.width = "3px";
    arrows.style.position = "absolute";
    arrows.style.top = arrow.offsetTop + "px";
    arrows.style.left = arrow.offsetLeft + "px";
};
#arrow {
    height: 80px;
    width: 3px;
    background: black;
    position: relative;
    -webkit-animation: move 5s infinite; /* Safari 4.0 - 8.0 */
    animation: move 5s infinite;
}

/* Styles for animating arrow */
/* Safari 4.0 - 8.0 */
@-webkit-keyframes move {
  from {left: 0px;}
  to {left: 400px;}
}

@keyframes move {
  from {left: 0px;}
  to {left: 400px;}
}
<div id="arrow"></div>
<button id="button" onclick="shot();"> Shot! </button>


推荐阅读