我有这段代码:
<script type="text/javascript">
var total_images = 4;
var random_number = Math.floor((Math.random()*total_images));
var random_img = new Array();
random_img[0] = '<a href="page1.html"><img src="img/logo (0).jpg"></a>';
random_img[1] = '<a href="page2.html"><img src="img/logo (1).jpg"></a>';
random_img[2] = '<a href="page3.html"><img src="img/logo (2).jpg"></a>';
random_img[3] = '<a href="page1.html"><img src="img/logo (3).jpg"></a>';
document.write(random_img[random_number]);
此代码从文件夹中获取一些照片并将其显示在文档顶部。我有两个问题:
如何使用ID为boom1在div中显示图像?
如何为每张图片选择自定义尺寸?
感谢。
答案 0 :(得分:2)
您应该避免使用document.write,因为您无法控制输出。尝试类似的事情:
var total_images = 4;
var random_number = Math.floor((Math.random()*total_images));
var random_img = [];
var target = document.getElementById('boom1');
random_img.push('<a href="page1.html"><img src="img/logo (0).jpg"></a>');
random_img.push('<a href="page2.html"><img src="img/logo (1).jpg"></a>');
random_img.push('<a href="page3.html"><img src="img/logo (2).jpg"></a>');
random_img.push('<a href="page1.html"><img src="img/logo (3).jpg"></a>');
// sizes can be set by adding width="" height="" in the img tag
target.innerHTML = random_img[random_number];
确保代码在DOM中呈现boom1
元素后运行
答案 1 :(得分:1)
var random_img = new Array();
random_img[0] = '<a href="page1.html"><img src="img/logo (0).jpg"></a>';
random_img[1] = '<a href="page2.html"><img src="img/logo (1).jpg"></a>';
random_img[2] = '<a href="page3.html"><img src="img/logo (2).jpg"></a>';
random_img[3] = '<a href="page1.html"><img src="img/logo (3).jpg"></a>';
for(var count=0; count < random_img.length; count++){
$("#divID").append(random_img[count]);
$("#divID").append('<br/>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="Main"> </div>
var random_img = new Array();
random_img [0] ='';
random_img [1] ='';
random_img [2] ='';
random_img [3] ='';
for(var count = 0; count&lt; random_img.length; count ++)
{
$("#divID").append(random_img[count]);
$("#divID").append('<br/>');
}
答案 2 :(得分:0)
<强>尺寸强>
<img src="blah blah" height="30px" width="30px">
自定义写入
HTML
<div id="hi"></div>
JS
document.getElementById("hi").innerHTML = "<p>hi</p>";
答案 3 :(得分:0)
两种方式。将图像元素附加到Div或将图像设置为背景图像。
首先:
var div = document.getElementById('boom1');
div.innerHTML = div.innerHTML + '<img src="...." width="...." height="...." >';
第二
var div = document.getElementById('boom1');
div.style.backgroundImage = "url('....')";
div.style.backgroundSize = "100px 100px";