gpt4 book ai didi

Javascript 图像和文本数组格式化

转载 作者:行者123 更新时间:2023-11-28 07:25:27 25 4
gpt4 key购买 nike

对于我的网站,我正在创建一个数组,每次都会随机显示图像和关联的文本。我已经让数组正常工作,但第一行文本从右下角或图像开始。如何使图像向左对齐并使文本与图像一起从顶部开始?

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]);

最佳答案

首先不要使用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>

关于Javascript 图像和文本数组格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29720665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com