javascript - AppendChild 除了另一个元素
问题描述
我是 JS 新手——所以我直接请求道歉。
我正在使用 appendchild 创建一个简单的 div。这个动作是由一个按钮完成的。问题是每次我按下按钮时,它都会在前一个正方形下方创建一个新正方形 - 不是除此之外。除了它我该怎么做?
<html>
<head>
<title>RocketSeat - Challenge 1</title>
</head>
<body>
<button onclick="MakeSquare()" style="margin-top: 100px;">Make a square</button>
</body>
<script>
function MakeSquare(){
const square = document.createElement('div')
const elementBody = document.querySelector('body')
square.style.backgroundColor ='red'
square.style.width = '50px'
square.style.height = '50px'
square.style.marginTop= '50px'
square.style.border = '1px solid red'
elementBody.appendChild(square)
}
</script>
</html>
解决方案
似乎是 CSS(样式)问题,试试这个:
<html>
<head>
<title>RocketSeat - Challenge 1</title>
</head>
<body>
<button onclick="MakeSquare()" style="margin-top: 100px;">Make a square</button>
</body>
<script>
function MakeSquare() {
const square = document.createElement('div')
const elementBody = document.querySelector('body')
square.style.backgroundColor = 'red'
square.style.width = '50px'
square.style.height = '50px'
square.style.marginTop = '50px'
square.style.border = '1px solid red'
square.style.display = 'inline-block' // added display styling
elementBody.appendChild(square)
}
</script>
</html>
推荐阅读
- ruby-on-rails - How to find or update a record though a nested attributes form (Rails 6)
- azure - 如何将 Kusto 查询与 2 个表列进行比较?
- html - How to offset for scrollbar width with css?
- python - Unable to install pycryptodome-3.3.1.tar.gz
- blazor - Use different layout in lazy loaded assembly
- javascript - AJAX POST not sending request to express.js server with body-parser due CORS problem (SOLVED)
- visual-studio - Asynchronous callback not working in VSTS/Azure DevOps
- kubernetes - Cert-Manager: renewing dns01 certificate not working
- html - Angular10 响应式表单验证模糊和提交
- django - TypeError:“发布”对象不可调用