刚开始,我是编程的新手,但总是想进入它。作为第一个练习,我想用html制作一个小画廊。到现在为止还挺好。然后我提出了一个我试图为自己解决的小问题:是否有可能在每次重新加载页面时将图像调整到一个范围内(让我们说高度从1-1000px变化)。我用var x = Math.floor((Math.random() * 1000) + 1);
命令尝试了几个javascripts,但不知怎么管理。据我所知,在CSS中无法做到这一点?所以高度会变化并且每次都会改变,而宽度总是会调整....
<!DOCTYPE html>
<head>
<script>
var imgs = document.querySelectorAll('img.resizable');
for (var i = 0; i < imgs.length; i++){
imgs[i].style.setProperty('--image-height', Math.floor(Math.random() * 1000) + 1 + 'px');
</script>
<style>
figure {
display: inline-block;
margin: 0px;
border-left: 10px;
margin-left: 20px;
vertical-align:top;
}
img.resizable {
height : calc(var(--image-height));
width: auto;
}
figcaption{
font-size: 10px;
line-height: 2px;
text-align: left;
margin-top: 10px;
}
</style>
</head>
<main>
<figure>
<img src="pic1" class = "resizable">
<figcaption>
<p>CAPTIONimg1</p>
</figcaption>
</figure>
<figure>
<img src="pic2" class = "resizable">
<figcaption>
<p>CAPTIONimg2</p>
</figcaption>
</figure>
<figure>
<img src="pic3" class = "resizable">
<figcaption>
<p>CAPTIONimg3</p>
</figcaption>
</figure>
<figure>
<img src="pic4" class = "resizable">
<figcaption>
<p>CAPTIONimg4</p>
</figcaption>
</figure>
<p> </p>
答案 0 :(得分:0)
你快到了:
var images = document.getElementsByTagName('img');//SELECT ALL THE IMAGES
for(var i = 0; i < images.length; i++) {//ITERATE THROUGH ALL THE IMAGES
images[i].style.height=Math.floor((Math.random() * 1000) + 1);//APPLY THE RANDOM HEIGHT TO EACH IMAGE
images[i].style.width="auto";//MAKE THE WIDTH CORRESPOND PROPORTIONALLY
}
答案 1 :(得分:0)
有更简单的方法,但这里有一个使用css变量:
var imgs = document.querySelectorAll('img.resizable');
for (var i = 0; i < imgs.length; i++){
imgs[i].style.setProperty('--image-height', Math.floor(Math.random() * 1000) + 1 + 'px');
}
img.resizable {
height : calc(var(--image-height));
width: auto;
}
<img class = "resizable" src = "http://lorempixel.com/200/200">
<img class = "resizable" src = "http://lorempixel.com/200/200">