2015-04-18 57 views
1

對於我的網站,我創建了一個隨機顯示圖像和相關文本的數組。我已經獲得了該陣列的工作,但第一行文本從右下角或圖像開始。如何讓圖像左移,文字從圖像的頂部開始?Javascript圖像和文本數組格式化

var r_text = new Array(); 
 
r_text[0] = "<em>Adrian's online program is totally unique and his approach is founded on the principle that your career should really just be another way to express yourself. I am deeply grateful to have found a more fitting career in brand management and I hope to start a business down the road.</em><br>Matt, San Francisco"; 
 
r_text[1] = "<em>I can tell you that after 3+ months using this career pathfinding program that my career outlook has never been better! I am currently going through a complete career change that I would have never dreamed about before I started this program. </em><br>Conrad, San Francisco"; 
 
var random_img = new Array(); 
 
random_img[0] = '<img src="http://lorempixel.com/100/100/nature/1">'; 
 
random_img[1] = '<img src="http://lorempixel.com/100/100/nature/2">'; 
 
var total_testimonials = 2; 
 
var random_number = Math.floor((Math.random()*total_testimonials)); 
 
document.write(random_img[random_number]); 
 
document.write(r_text[random_number]);

+0

你的意思是像CSS的'浮動:左;'? – Xufox

+1

這真的不是一個JavaScript問題;它關於HTML和CSS。請重新編寫您的問題,重點關注這些問題。 –

+0

'document.write'和'new Array'在JavaScript中都是非常糟糕的做法。考慮使用'document.createElement'(加上它附加到DOM),並簡單地'var foo = []'。 –

回答

0

首先不使用document.write,它在非常特殊的情況下的二手和極少。如果你想渲染一些HTML內容,你應該使用許多其他的DOM操作方法。在我的示例中,我將使用document.querySelector方法搜索必需的容器元素,並使用innerHTML屬性設置其內部HTML內容。

然後,您應該考慮爲您的推薦文字和圖片添加最初的HTML結構,您將在其中添加隨機內容。

最後,當內容位於DOM中時,您可能需要使用CSS對其進行設置。在你的情況下,你想要使圖像float to the left,這將使文本從右側溢出。

如果上述修復問題的代碼可能會開始尋找這樣的事情:

var r_text = [ 
 
    "<em>Adrian's online program is totally unique and his approach is founded on the principle that your career should really just be another way to express yourself. I am deeply grateful to have found a more fitting career in brand management and I hope to start a business down the road.</em><br>Matt, San Francisco", 
 
    "<em>I can tell you that after 3+ months using this career pathfinding program that my career outlook has never been better! I am currently going through a complete career change that I would have never dreamed about before I started this program. </em><br>Conrad, San Francisco"]; 
 

 
var random_img = [ 
 
    '<img src="http://lorempixel.com/100/100/nature/1">', 
 
    '<img src="http://lorempixel.com/100/100/nature/2">' 
 
]; 
 

 
var total_testimonials = r_text.length; 
 
var random_number = Math.floor((Math.random() * total_testimonials)); 
 

 
document.querySelector('.container .image').innerHTML = random_img[random_number]; 
 
document.querySelector('.container .testimonial').innerHTML = r_text[random_number];
.container { 
 
    overflow: auto; 
 
    padding: 10px; 
 
} 
 
.container .image { 
 
    float: left; 
 
    margin-right: 10px; 
 
}
<div class="container"> 
 
    <div class="image"></div> 
 
    <div class="testimonial"></div> 
 
</div>