【问题标题】:js resizing images upon reload of pagejs在重新加载页面时调整图像大小
【发布时间】:2018-02-15 06:42:17
【问题描述】:

刚开始,我对编程还是个新手,但一直想进入它。作为第一个练习,我想用 html 制作一个小画廊。到目前为止,一切都很好。然后我想出了一个我试图为自己解决的小问题:每次我重新加载页面时,是否可以在一个范围内调整图像大小(假设高度从 1-1000 像素变化)。我用var x = Math.floor((Math.random() * 1000) + 1); 命令尝试了几个javascript,但不知何故无法管理。据我所知,在 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>&nbsp;</p>  

【问题讨论】:

    标签: javascript html image resize


    【解决方案1】:

    有更简单的方法,但这里有一种使用 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">

    【讨论】:

    • 看起来是个不错的解决方案! js 虽然需要放在每张图片的前面,对吗?或者我可以在一开始就拥有它,然后它不会为每张图像计算相同的高度吗?谢谢!
    • @flo 取决于您是希望所有图像都使用相同的缩放比例还是每个图像缩放比例相同
    • 其实我以为每张图片都可以自己缩放,那么我猜CSS标签是不够的,对吗?是否可以使用脚本定义每个高度值?
    • 非常感谢!我刚刚编辑了上面的代码,不知何故我错过了整个事情,似乎没有任何工作:对不起,对此很陌生......
    • @flo 您缺少 for 循环中的结束 }。此外,您需要将代码包含在 window.onload = function(){...} 中。如果没有,代码将在图像节点渲染之前运行,因此届时将有 0 个元素来改变高度
    【解决方案2】:

    你快到了:

            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
        }
    

    【讨论】:

      猜你喜欢
      • 2014-05-26
      • 1970-01-01
      • 2017-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-08
      • 2012-11-21
      相关资源
      最近更新 更多