为什么当我运行函数createRect()
时红色矩形没有出现。任何帮助将不胜感激。
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tetris(test)</title>
<link rel="stylesheet" href="styleSheets/main.css">
<script src = "https://code.jquery.com/jquery-3.4.1.js"></script>
<script src = "js/jquery.1.js"></script>
<script src = "js/main.js"></script>
</head>
<body>
<svg id="container" width= "500" height= "650" style= "background-color: black" position= "relative">
</svg>
</body>
</html>
function createRect() {
var rec = document.createElement("rect");
rec.style.width = "100px";
rec.style.height = "100px";
rec.style.left = "0px";
rec.style.top = "0px";
rec.style.fill = "red";
rec.style.position = "absolute";
var elem = document.getElementById("container");
elem.append(rec);
}
window.onload = createRect;
在运行此功能后,左上角会出现一个红色框。
也许是
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tetris(test)</title>
<link rel="stylesheet" href="styleSheets/main.css">
<script src = "https://code.jquery.com/jquery-3.4.1.js"></script>
<script src = "js/jquery.1.js"></script>
<script src = "js/main.js"></script>
</head>
<body>
<svg id="container" width= "500" height= "650" style= "background-color: black">
</svg>
</body>
</html>
<script>
function createRect() {
const svgNS = "http://www.w3.org/2000/svg";
const svg = document.querySelector("svg");
const rec = document.createElementNS(svgNS ,'rect');
rec.setAttribute('width', 100);
rec.setAttribute('height', 100);
rec.setAttribute('x', 50);
rec.setAttribute('y', 50);
rec.setAttribute('fill', 'red');
svg.appendChild(rec);
}
window.onload = createRect;
</script>
function createRect() {
var rec = document.createElementNS('http://www.w3.org/2000/svg',"rect");
rec.style.width = "100px";
rec.style.height = "100px";
rec.style.left = "0px";
rec.style.top = "0px";
rec.style.fill = "red";
rec.style.position = "relative";
var elem = document.getElementById("container");
elem.append(rec);
}