簡體   English   中英

移動已經用 JavaScript 創建的按鈕

[英]Moving a button that has already been created with JavaScript

在這里我嘗試創建一個用於創建按鈕的 JS 函數,我已經成功地做到了。 對我不起作用的是找到一種方法來在同一功能中移動/定位該按鈕。 我在互聯網上尋找答案,但找不到。

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 類並將其包含在 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");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM