簡體   English   中英

無法在按鈕之間使用“innerHTML”添加空格

[英]Can not add white space with 'innerHTML' between buttons

我有這個 javascript 用於在兩個按鈕之間添加空白,我剛剛創建並插入了一個div

document.getElementById("divID").appendChild(buttonONE);

document.getElementById("divID").innerHTML + ="           ";

document.getElementById("divID").appendChild(buttonTWO);

兩個按鈕之間有一個空格,但始終只有一個空格,就像您只按了一次空格鍵一樣。

如何將這些空間增加到一個以上?

謝謝

  1. HTML 中的所有空白,包括換行符,都減少到只有一個空格。 這就是規則。

  2. 不要使用空格。 它們並不准確。 使用一個元素並在 CSS 中為其指定寬度、填充或邊距。

  3. 如果您必須使用空格,請使用  . 這是一個不間斷的空間,所有這些都被打印出來。 但真的,不要使用它。

你必須使用  (不間斷空格)用於每個空格,以防止瀏覽器將其顯示為一個空格。

如果您不是在尋找指定的長度,請使用 html 實體  ,
否則使用margin-left:10px;
在 JavaScript 中使用:
window.onload = function(){ var element = document.getElementById("Element-Id"); element.style.marginLeft = "20px";
您不需要window.onload = function(){} ,但您確實需要確保該函數在加載后才執行(您可能知道。)

 var b; b = 0; function move() { var a = document.getElementById("example"); b += 20; a.style.marginLeft = b + "px" // For moving a specified amount, just remove var b, b = 0, b+=20; and then replace a.style.marginLeft = b+"px"with a.style.marginLeft = "[amount]"; }
 button{ outline:0; border-radius:35%; border-width:0; background-color:red; color:white; cursor:pointer; } button:hover{ color:red; background-color:blue; } a{ cursor:default; border-radius:10%; border-width:10%; }
 <html> <head> <title>Example</title> <head> <body> <button onclick="move()">Move the text 20px to the left.</button><br> <a style="background-color:black;color:white;" id="example">Example</a> </body> </html>

CSS 解決方案怎么樣? 你可以給元素一個 ID 並使用一個 ID 選擇器:

 #buttonTWO
    {
       margin-left: 20px;
    }

或者如果您不能使用 CSS 使用 Javascript 設置它:

document.getElementById("divID").appendChild(document.getElementById("buttonONE"));
var buttonTwo = document.getElementById("buttonTWO");
buttonTwo.style.marginLeft = "20px";
document.getElementById("divID").appendChild(buttonTwo);

http://jsfiddle.net/Std8J/

我相信你會因為 html 剝離空間的性質而得到這個。

您也許可以在要呈現該文本的任何元素上使用 white-space: pre css 屬性。

<div id="divID" style="white-space: pre"></div>

我不太了解你的申請,但也許這就足夠了。

(這是遲到的答案,但它會像我在尋找解決方案時那樣登陸此頁面的其他人受益)

使用 html 的 pre 標簽解決了我的問題。

我正在顯示一個數組,該數組有時會有多個空格,我需要保留它而不將其減少為一個空格。

如果您使用 replaceAll(' ', ' ')。 你會得到你想要的預期結果

暫無
暫無

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

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