我正在尝试创建一个横幅,在每次刷新时显示随机图像。我已经设法让它工作,但我需要将图像的高度更改为139px,而不是让它们以完整大小显示。如何在随机加载图像的脚本中设置图像的高度?
我15年前在学校学习了代码,所以我现在对它的理解基本上是0,所以我很容易迷失!可能有更好的方法来加载随机图像,但这是我唯一能够开始工作的方法。
<div style="position:absolute;top:0;left:1072;height:139px;overflow:hidden;" class="banner3"></div>
<script>
var randomImage = {
paths: [
"c1.png",
"c2.png",
"c3.png",
"c4.png",
"c5.png",
"c6.png",
"c7.png",
],
generate: function(){
var path = randomImage.paths[Math.floor(Math.random()*randomImage.paths.length)];
var img = new Image();
img.src = path;
$("div.banner3").html(img);
}
}
randomImage.generate();
</script>
使用document.createElement而不是image,如下所示:
var randomImage = {
paths: [
"c1.png",
"c2.png",
"c3.png",
"c4.png",
"c5.png",
"c6.png",
"c7.png",
],
generate: function(){
var path = randomImage.paths[Math.floor(Math.random()*randomImage.paths.length)];
var img = document.createElement('img');
img.src = path;
img.height = DESIRED HEIGHT
$("div.banner3").html(img);
}
}
randomImage.generate();
你可以试试这个:
var path = randomImage.paths[Math.floor(Math.random()*randomImage.paths.length)];
var img = new Image();
img.src = path;
在此之后你可以添加:
img.style.height = '139px';
然后将其设置为html:
$("div.banner3").html(img);
你可以用CSS做到这一点:
var randomImage = {
paths: [ "https://picsum.photos/id/1/300/300",
"https://picsum.photos/id/2/300/300",
"https://picsum.photos/id/3/300/300",
"https://picsum.photos/id/4/300/300",
"https://picsum.photos/id/5/300/300",
"https://picsum.photos/id/6/300/300",
"https://picsum.photos/id/7/300/300" ],
generate: function(){
var path = randomImage.paths[Math.floor(Math.random()*randomImage.paths.length)];
var img = new Image();
img.src = path;
$("div.banner3").html(img);
}
}
randomImage.generate();
.banner3 {
position: absolute;
top: 0;
left: 0;
height: 139px;
overflow: hidden
}
.banner3 img {
height: 139px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="banner3"></div>