Javascript图像和文本数组格式

时间:2015-04-18 17:42:07

标签: 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]);
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分: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>