移动已使用 JavaScript 创建的按钮

Moving a button that has already been created with JavaScript

我在这里尝试创建一个用于创建按钮的 JS 函数,我已经成功完成了。对我没有用的是在同一功能中找到 move/position 该按钮的方法。我在 Internet 上搜索了答案,但找不到。

function createButtons(dialogueString, buttonIdString) {
    var btn = document.createElement("button");
    btn.style.left = "50%"; //here is one of my attempts to move the button but it is not working
    btn.id = buttonIdString;
    btn.innerHTML = dialogueString;
    document.body.appendChild(btn);
};
createButtons("Hello", "choice1");

正如您在上面看到的,我尝试使用 btn.style.left 将按钮向左移动,我尝试写“200px”而不是“50%”和许多其他内容,但没有任何效果。如果您知道如何解决这个问题,请告诉我,我将不胜感激。

你可以用 css class 所需的样式并将其包含在 js 中。

例如:

//style.css
.buttonStyle{
  color: red;
}

//javascript part
btn.classList.add("buttonStyle");

找到解决方案。 我做了 btn.style.marginLeft = "+50px",它似乎有效。

只需将 btn.style.position = 'absolute';btn.style.position = 'relativ'; 添加到您的函数中

function createButtons(dialogueString, buttonIdString) {
    var btn = document.createElement("button");
    btn.style.left = "50%"; //here is one of my attempts to move the button but it is not working
    btn.style.position = 'absolute';
    btn.id = buttonIdString;
    btn.innerHTML = dialogueString;
    document.body.appendChild(btn);
};
createButtons("Hello", "choice1");