2011-02-26 43 views
1

我有一個返回字符串的JavaScript函數。我想將這個字符串寫入一個html頁面,但是以一個可以指定寬度的文本塊格式。我目前使用只讀textarea,但我確定有更好的方法。我將如何做到這一點?如何在html中顯示字符串作爲文本塊

例子:

字符串從JavaScript函數返回:
The dog was lazy in the sun.

在HTML頁面:

The dog was 
lazy in the 
sun. 

編輯:

對不起,我不是足夠清楚。 此javascript函數可能會返回任何字符串,我不知道它可能會返回什麼。 所以我的HTML中,我將做到以下幾點:

<script type="text/javascript" /> 
    document.write(functionCall()); 
</script> 

,但我想在例如格式化這個像上面。 不幸的是,使用width屬性對<div>標記進行打包時不起作用。

回答

0
var text, width, container; 

width = "200px";  // set this to whatever you like 
text = some_function(); 

// you can create a <div id="text-container"></div> in your 
// HTML wherever you want the text to show up, or you can 
// the JavaScript just create it at the bottom of the page 

container = document.getElementById("text-container"); 
if(!container) { 
    container = document.createElement("div"); 
    container.id = "text-container"; 
    document.body.appendChild(container); 
} 

container.style.width=width; 
container.innerHTML = text; 
+0

感謝這正是我想要的。 – CodeNewbie 2011-02-26 06:06:01

0

放置在一個<pre>標籤的文字,畢竟它代表了預格式化文本。

http://www.w3schools.com/tags/tag_pre.asp

然後,您可以使用CSS來控制元素的寬度:

pre { 
    width: 100px; 
} 

這種方法你可以交替添加斷絃本身,並把它添加到<pre>標籤,它將被格式化(並且您不需要寬度)。

0

您可以通過fixind在DIV做到這一點的寬度等作爲offex說

<div style="width:200px"></div>

一個桌子,上面有一個寬度

<table width="200px"></table>

相關問題