CSS/HTML/JS – GetElementByID 和 HTML/JS 元素间的间距问题

huangapple go评论85阅读模式
英文:

CSS/HTML/JS - GetElementByID and html/js element spacing issue

问题

我是一个JavaScript/HTML/CSS编程的业余爱好者。我开发了一个Java后端,正在开发一个方便的前端Web界面。我想以树形格式显示按钮。一切都成功了,除了两个问题:1) 我无法使按钮的间距工作。我试图在每一行的按钮之间实现均匀的间距。2) 即使使用onload,我也无法通过属性ID获取元素。检查页面显示元素和ID。如果我的代码混乱,我为此道歉。

以下是您提供的代码的翻译部分:

getTree();
addButtons();
window.onload = function() {
  let canvas = document.getElementById("canvas");
  let ctx = canvas.getContext('2d');
  ctx.beginPath();
  canvas_arrow(ctx, document.getElementById("rank1").x,
    document.getElementById("rank1").y,
    document.getElementById("rank2").x,
    document.getElementById("rank2").y);
  ctx.strokeStyle = '#ffffff';
  ctx.stroke();
};

function addButtons() {
  fetch('/api/tree').then(async (response) => {
    await response.json().then(result => {
      let i = 0;
      result.forEach(function(item) {
        let section = document.getElementById("rankButtons");
        let element = document.createElement("button");
        if (i !== item["tier"]) {
          section.appendChild(document.createElement("br"));
          section.appendChild(document.createElement("br"));
          i = item["tier"];
        }
        element.id = item["rankID"];
        element.value = item["rankName"];
        element.name = "rankButton";
        element.textContent = item["rankName"];
        section.appendChild(element);
      });
    })
  }).catch(error => {
    console.log(error)
  })
}

function canvas_arrow(context, fromX, fromY, toX, toY) {
  let headLength = 10; // 头部长度(以像素为单位)
  let dx = toX - fromX;
  let dy = toY - fromY;
  let angle = Math.atan2(dy, dx);
  context.moveTo(fromX, fromY);
  context.lineTo(toX, toY);
  context.lineTo(toX - headLength * Math.cos(angle - Math.PI / 6), toY - headLength * Math.sin(angle - Math.PI / 6));
  context.moveTo(toX, toY);
  context.lineTo(toX - headLength * Math.cos(angle + Math.PI / 6), toY - headLength * Math.sin(angle + Math.PI / 6));
}
.header img {
  float: left;
  width: 100px;
  height: 100px;
  background: #555;
}

body {
  color: white;
  opacity: 1;
}

table,
th,
td {
  border: 2px solid white;
  opacity: 1;
  margin: auto;
  text-align: center;
  width: 80%;
  table-layout: fixed;
}

td {
  white-space: pre;
  padding: 5px;
}

button {
  background: linear-gradient(to bottom right, #CC0033, #3300CC);
  padding: 5px;
  -webkit-border-radius: 0px;
  -moz-border-radius: 0px;
  resize: none;
  border: 1px solid #30273a;
  box-shadow: 0 0 10px #8d78a5;
  border-radius: 15px 15px 15px 15px;
  z-index: 2;
  position: relative;
}

#content {
  margin: 100px auto 0;
  width: 750px;
  max-width: 80%;
  padding: 0 0 40px;
  text-align: center;
  position: relative;
}

#viewport {
  height: 100%;
  width: 100%;
  position: relative;
}
<!DOCTYPE html>
<html lang="en" style="background-color: black">
<head>
  <div class="header">
    <img src="./RDQ-512-Logo.jpg" alt="logo">
  </div>
  <meta charset="UTF-8">
  <title id="title">Rank Up Tree</title>
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <link rel="stylesheet" href="tree.css">
</head>
<body>
<details>
  <summary style="text-align: center; font-size: 20px">Available Ranks</summary>
  <pre v-pre="true" class="prismjs line-numbers" style="text-align: center">
    <table id="ranks" class="table table-striped" style="font-size:12px"></table>
  </pre>
</details>
<canvas id="canvas" width="400" height="500" style="border:1px solid #000000"></canvas>
<div id="content">
  <div id="rankButtons"></div>
</div>
<script src="tree.js"></script>
</body>
</html>
英文:

I am an amatuer at javascript/html/css programing. I developed a java backend and I am in the process of developing a convenient frontend webui for it. I want to display buttons in a tree format. All has been successful accept two things: 1) I cannot get the spacing on my buttons to work. I am trying to attempt even spacing between buttons on each line. 2) I cannot get an element by a property ID even using onload. Inspecting the page shows the element and the ID. Apologies if my code is sloppy.

Image removed because everyone seems to focus on it for the wrong reason.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

getTree();
addButtons();
window.onload = function() {
let canvas = document.getElementById(&quot;canvas&quot;);
let ctx = canvas.getContext(&#39;2d&#39;);
ctx.beginPath();
canvas_arrow(ctx, document.getElementById(&quot;rank1&quot;).x,
document.getElementById(&quot;rank1&quot;).y,
document.getElementById(&quot;rank2&quot;).x,
document.getElementById(&quot;rank2&quot;).y);
ctx.strokeStyle = &#39;#ffffff&#39;;
ctx.stroke();
};
function addButtons() {
fetch(&#39;/api/tree&#39;).then(async(response) =&gt; {
await response.json().then(result =&gt; {
let i = 0;
result.forEach(function(item) {
let section = document.getElementById(&quot;rankButtons&quot;);
let element = document.createElement(&quot;button&quot;);
if (i !== item[&quot;tier&quot;]) {
section.appendChild(document.createElement(&quot;br&quot;));
section.appendChild(document.createElement(&quot;br&quot;));
i = item[&quot;tier&quot;];
}
element.id = item[&quot;rankID&quot;];
element.value = item[&quot;rankName&quot;];
element.name = &quot;rankButton&quot;;
element.textContent = item[&quot;rankName&quot;];
section.appendChild(element);
});
})
}).catch(error =&gt; {
console.log(error)
})
}
function canvas_arrow(context, fromX, fromY, toX, toY) {
let headLength = 10; // length of head in pixels
let dx = toX - fromX;
let dy = toY - fromY;
let angle = Math.atan2(dy, dx);
context.moveTo(fromX, fromY);
context.lineTo(toX, toY);
context.lineTo(toX - headLength * Math.cos(angle - Math.PI / 6), toY - headLength * Math.sin(angle - Math.PI / 6));
context.moveTo(toX, toY);
context.lineTo(toX - headLength * Math.cos(angle + Math.PI / 6), toY - headLength * Math.sin(angle + Math.PI / 6));

}

<!-- language: lang-css -->

.header img {
float: left;
width: 100px;
height: 100px;
background: #555;
}
body {
color: white;
opacity: 1;
}
table,
th,
td {
border: 2px solid white;
opacity: 1;
margin: auto;
text-align: center;
width: 80%;
table-layout: fixed;
}
td {
white-space: pre;
padding: 5px;
}
button {
background: linear-gradient(to bottom right, #CC0033, #3300CC);
padding: 5px;
-webkit-border-radius: 0px;
-moz-border-radius: 0px;
resize: none;
border: 1px solid #30273a;
box-shadow: 0 0 10px #8d78a5;
border-radius: 15px 15px 15px 15px;
z-index: 2;
position: relative;
}
#content {
margin: 100px auto 0;
width: 750px;
max-width: 80%;
padding: 0 0 40px;
text-align: center;
position: relative;
}
#viewport {
height: 100%;
width: 100%;
position: relative;
}

tree.html
<!-- language: lang-html -->

&lt;script src=&quot;https://code.jquery.com/jquery-3.5.1.min.js&quot;&gt;&lt;/script&gt;
&lt;details&gt;
&lt;summary style=&quot;text-align: center; font-size: 20px&quot;&gt;Available Ranks&lt;/summary&gt;
&lt;pre v-pre=&quot;true&quot; class=&quot;prismjs line-numbers&quot; style=&quot;text-align: center&quot;&gt;
&lt;table id=&quot;ranks&quot; class=&quot;table table-striped&quot; style=&quot;font-size:12px&quot;&gt;&lt;/table&gt;
&lt;/pre&gt;
&lt;/details&gt;
&lt;canvas id=&quot;canvas&quot; width=&quot;400&quot; height=&quot;500&quot; style=&quot;border:1px solid #000000;&quot;&gt;
&lt;div id=&quot;content&quot;&gt;
&lt;div id=&quot;rankButtons&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

<!-- end snippet -->

Here it is again because the other guy edited it out...

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; style=&quot;background-color: black&quot;&gt;
&lt;head&gt;
&lt;div class=&quot;header&quot;&gt;
&lt;img src=&quot;./RDQ-512-Logo.jpg&quot; alt=&quot;logo&quot;&gt;
&lt;/div&gt;
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;title id=&quot;title&quot;&gt;Rank Up Tree&lt;/title&gt;
&lt;script src=&quot;https://code.jquery.com/jquery-3.5.1.min.js&quot;&gt;&lt;/script&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;tree.css&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;details&gt;
&lt;summary style=&quot;text-align: center; font-size: 20px&quot;&gt;Available Ranks&lt;/summary&gt;
&lt;pre v-pre=&quot;true&quot; class=&quot;prismjs line-numbers&quot; style=&quot;text-align: center&quot;&gt;
&lt;table id=&quot;ranks&quot; class=&quot;table table-striped&quot; style=&quot;font-size:12px&quot;&gt;&lt;/table&gt;
&lt;/pre&gt;
&lt;/details&gt;
&lt;canvas id=&quot;canvas&quot; width=&quot;400&quot; height=&quot;500&quot; style=&quot;border:1px solid #000000;&quot;&gt;
&lt;/canvas&gt;
&lt;div id=&quot;content&quot;&gt;
&lt;div id=&quot;rankButtons&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;tree.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

答案1

得分: 2

你现在是我的中文翻译,代码部分不要翻译,只返回翻译好的部分,不要有别的内容,不要回答我要翻译的问题。以下是要翻译的内容:

### You are over-complicating your functions

Async functions are designed to be easy to read.

Surely the top only needs to be:

### You are not calling `addButtons` anywhere

You say this is your entire front-end code. Well that doesn't call addButtons.

### I suspect you want to create the buttons first

You seem to be trying in your `onLoad` to access elements with ID=`rank1` etc, which seem to be being created by `addButtons`.

Therefore did you want to run `addButtons` first?

If so, since `addButtons` is asynchronous, you should `await` it. (I have added a `return true` to the function as a reminder that it will return a promise.)
英文:

You are over-complicating your functions

function addButtons() {
fetch(&#39;/api/tree&#39;).then(async(response) =&gt; {
await response.json().then(result =&gt; {
let i = 0;
result.forEach(function(item) {
let section = document.getElementById(&quot;rankButtons&quot;);
let element = document.createElement(&quot;button&quot;);
if (i !== item[&quot;tier&quot;]) {
section.appendChild(document.createElement(&quot;br&quot;));
section.appendChild(document.createElement(&quot;br&quot;));
i = item[&quot;tier&quot;];
}
element.id = item[&quot;rankID&quot;];
element.value = item[&quot;rankName&quot;];
element.name = &quot;rankButton&quot;;
element.textContent = item[&quot;rankName&quot;];
section.appendChild(element);
});
})
return true
}).catch(error =&gt; {
console.log(error)
})
}

Async functions are designed to be easy to read.

Surely the top only needs to be:

async function addButtons(){
const response = await fetch(&#39;/api/tree&#39;);
const result = await response.json();
let i=0;
// ... etc
}

You are not calling addButtons anywhere

You say this is your entire front-end code. Well that doesn't call addButtons.

I suspect you want to create the buttons first

You seem to be trying in your onLoad to access elements with ID=rank1 etc, which seem to be being created by addButtons.

Therefore did you want to run addButtons first?

If so, since addButtons is asynchronous, you should await it. (I have added a return true to the function as a reminder that it will return a promise.)

window.onload = async function() {
await addButtons()
let canvas = document.getElementById(&quot;canvas&quot;);
let ctx = canvas.getContext(&#39;2d&#39;);
ctx.beginPath();
canvas_arrow(ctx, document.getElementById(&quot;rank1&quot;).x,
document.getElementById(&quot;rank1&quot;).y,
document.getElementById(&quot;rank2&quot;).x,
document.getElementById(&quot;rank2&quot;).y);
ctx.strokeStyle = &#39;#ffffff&#39;;
ctx.stroke();
};
</details>
# 答案2
**得分**: 1
感谢 @Eureka 的帮助!在使用 findPos 重新编写 CSS 和 JavaScript 后,这是答案:
```javascript
function findPos(obj){
let curLeft = obj.offsetWidth / 2;
let curTop = obj.offsetHeight / 2;
if (obj.offsetParent) {
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj === obj.offsetParent);
return {x:curLeft,y:curTop};
}
}
window.onload = async function () {
await addButtons();
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext('2d');
ctx.beginPath();
let pos = findPos(document.getElementById("rank1"));
let pos2 = findPos(document.getElementById("rank2"));
canvas_arrow(ctx, pos.x, pos.y, pos2.x, pos2.y - 10);
ctx.strokeStyle = '#ffffff';
ctx.stroke();
};
function canvas_arrow(context, fromX, fromY, toX, toY) {
let headLength = 10; // 箭头长度(以像素为单位)
let dx = toX - fromX;
let dy = toY - fromY;
let angle = Math.atan2(dy, dx);
context.moveTo(fromX, fromY);
context.lineTo(toX, toY);
context.lineTo(toX - headLength * Math.cos(angle - Math.PI / 6), toY - headLength * Math.sin(angle - Math.PI / 6));
context.moveTo(toX, toY);
context.lineTo(toX - headLength * Math.cos(angle + Math.PI / 6), toY - headLength * Math.sin(angle + Math.PI / 6));
}
async function addButtons() {
const response = await fetch('/api/tree');
const result = await response.json();
let i = 0;
result.forEach(function (item) {
let section = document.getElementById("rankButtons");
let element = document.createElement("button");
if (i !== item["tier"]) {
section.appendChild(document.createElement("br"));
section.appendChild(document.createElement("br"));
i = item["tier"];
}
element.id = item["rankID"];
element.value = item["rankName"];
element.name = "rankButton";
element.style.background = "linear-gradient(to bottom right, #CC0033, #3300CC)";
element.style.padding = "5px";
element.textContent = item["rankName"];
section.appendChild(element);
});
}
```
```css
.header img {
float: left;
width: 100px;
height: 100px;
background: #555;
}
body {
color: white;
opacity: 1;
}
table, th, td {
border: 2px solid white;
opacity: 1;
margin: auto;
text-align: center;
width: 80%;
table-layout: fixed;
}
table {
display: block;
overflow-x: auto;
white-space: nowrap;
}
td {
white-space: pre;
padding: 5px;
}
#container {
height: 800px;
position: relative;
width: 800px;
text-align: center;
margin: auto;
}
#canvas {
height: 100%;
width: 100%;
z-index: -1;
position: relative;
border-color: white;
}
#rankButtons {
bottom: 100%;
left: 0;
position: relative;
width: 100%;
z-index: 1;
}
```
```html
<!DOCTYPE html>
<html lang="en" style="background-color: black">
<head>
<div class="header">
<img src="./RDQ-512-Logo.jpg" alt="logo">
</div>
<meta charset="UTF-8">
<title id="title">Rank Up Tree</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<link rel="stylesheet" href="tree.css">
</head>
<body>
<details>
<summary style="text-align: center; font-size: 20px">Available Ranks</summary>
<pre v-pre="true" class="prismjs line-numbers" style="text-align: center">
<table id="ranks" class="table table-striped" style="font-size:12px"></table>
</pre>
</details>
<div id="container">
<canvas id="canvas" width="800" height="800" style="border:1px solid #000000;">
</canvas>
<div id="rankButtons"></div>
</div>
<script src="tree.js"></script>
</body>
</html>
```
<details>
<summary>英文:</summary>
Thank you @Eureka for the help! After redoing the css and javascript using findPos this is the answer:
&lt;!-- begin snippet: js hide: false console: true babel: false --&gt;
&lt;!-- language: lang-js --&gt;
function findPos(obj){
let curLeft = obj.offsetWidth / 2;
let curTop = obj.offsetHeight / 2;
if (obj.offsetParent) {
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj === obj.offsetParent);
return {x:curLeft,y:curTop};
}
}
window.onload = async function () {
await addButtons();
let canvas = document.getElementById(&quot;canvas&quot;);
let ctx = canvas.getContext(&#39;2d&#39;);
ctx.beginPath();
let pos = findPos(document.getElementById(&quot;rank1&quot;));
let pos2 = findPos(document.getElementById(&quot;rank2&quot;));
canvas_arrow(ctx, pos.x, pos.y, pos2.x, pos2.y - 10);
ctx.strokeStyle = &#39;#ffffff&#39;;
ctx.stroke();
};
function canvas_arrow(context, fromX, fromY, toX, toY) {
let headLength = 10; // length of head in pixels
let dx = toX - fromX;
let dy = toY - fromY;
let angle = Math.atan2(dy, dx);
context.moveTo(fromX, fromY);
context.lineTo(toX, toY);
context.lineTo(toX - headLength * Math.cos(angle - Math.PI / 6), toY - headLength * Math.sin(angle - Math.PI / 6));
context.moveTo(toX, toY);
context.lineTo(toX - headLength * Math.cos(angle + Math.PI / 6), toY - headLength * Math.sin(angle + Math.PI / 6));
}
async function addButtons() {
const response = await fetch(&#39;/api/tree&#39;);
const result = await response.json();
let i = 0;
result.forEach(function (item) {
let section = document.getElementById(&quot;rankButtons&quot;);
let element = document.createElement(&quot;button&quot;);
if (i !== item[&quot;tier&quot;]) {
section.appendChild(document.createElement(&quot;br&quot;));
section.appendChild(document.createElement(&quot;br&quot;));
i = item[&quot;tier&quot;];
}
element.id = item[&quot;rankID&quot;];
element.value = item[&quot;rankName&quot;];
element.name = &quot;rankButton&quot;;
element.style.background = &quot;linear-gradient(to bottom right, #CC0033, #3300CC)&quot;;
element.style.padding = &quot;5px&quot;;
element.textContent = item[&quot;rankName&quot;];
section.appendChild(element);
});
}
&lt;!-- language: lang-css --&gt;
.header img {
float: left;
width: 100px;
height: 100px;
background: #555;
}
body {
color: white;
opacity: 1;
}
table, th, td {
border: 2px solid white;
opacity: 1;
margin: auto;
text-align: center;
width: 80%;
table-layout: fixed;
}
table {
display: block;
overflow-x: auto;
white-space: nowrap;
}
td {
white-space:pre;
padding: 5px;
}
#container {
height: 800px;
position: relative;
width: 800px;
text-align: center;
margin: auto;
}
#canvas {
height: 100%;
width: 100%;
z-index: -1;
position: relative;
border-color: white;
}
#rankButtons {
bottom: 100%;
left: 0;
position: relative;
width: 100%;
z-index: 1;
}
&lt;!-- language: lang-html --&gt;
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; style=&quot;background-color: black&quot;&gt;
&lt;head&gt;
&lt;div class=&quot;header&quot;&gt;
&lt;img src=&quot;./RDQ-512-Logo.jpg&quot; alt=&quot;logo&quot;&gt;
&lt;/div&gt;
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;title id=&quot;title&quot;&gt;Rank Up Tree&lt;/title&gt;
&lt;script src=&quot;https://code.jquery.com/jquery-3.5.1.min.js&quot;&gt;&lt;/script&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;tree.css&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;details&gt;
&lt;summary style=&quot;text-align: center; font-size: 20px&quot;&gt;Available Ranks&lt;/summary&gt;
&lt;pre v-pre=&quot;true&quot; class=&quot;prismjs line-numbers&quot; style=&quot;text-align: center&quot;&gt;
&lt;table id=&quot;ranks&quot; class=&quot;table table-striped&quot; style=&quot;font-size:12px&quot;&gt;&lt;/table&gt;
&lt;/pre&gt;
&lt;/details&gt;
&lt;div id=&quot;container&quot;&gt;
&lt;canvas id=&quot;canvas&quot; width=&quot;800&quot; height=&quot;800&quot; style=&quot;border:1px solid #000000;&quot;&gt;
&lt;/canvas&gt;
&lt;div id=&quot;rankButtons&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;tree.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
&lt;!-- end snippet --&gt;
</details>

huangapple
  • 本文由 发表于 2023年3月12日 09:07:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75710529.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定