Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript CSS按视口反转图像高度_Javascript_Css_Twitter Bootstrap - Fatal编程技术网

Javascript CSS按视口反转图像高度

Javascript CSS按视口反转图像高度,javascript,css,twitter-bootstrap,Javascript,Css,Twitter Bootstrap,当视口变小/最小化时,尝试进行图像缩放并将高度调整为更大的尺寸,而不是相反。例如,当我把一个窗口缩小时,图像在页面上会变长 background-image: url(../images/bgimg-aboutme.jpg); /* Settings */ /* Settings */ height: 50vmin; position: relative; background-position: center; backgrou

当视口变小/最小化时,尝试进行图像缩放并将高度调整为更大的尺寸,而不是相反。例如,当我把一个窗口缩小时,图像在页面上会变长

background-image: url(../images/bgimg-aboutme.jpg);
/* Settings */                                  /* Settings */
height: 50vmin;
position: relative;
background-position: center;
background-repeat: no-repeat;
background-size: cover;

请帮助我,我真的很想知道如何从js或其他语言做到这一点。谢谢大家!

这应该是如何在JavaScript中实现所需内容的基本示例。我们做了两个基本假设来计算图像的高度:对于包装收缩的视口高度的每一个百分比,图像将增加一个百分比。因此,如果包装是99vh,图像将是101vh

这个例子说明了你如何实现你想要的,你应该可以从这里开始

//获取图像
让imgObj=document.getElementById('image'))
//拿包装纸
让wrapper=document.getElementsByClassName('image-wrapper')[0]
//获取视口高度
让viewPort=window.innerHeight
//获取包装高度
设wrapperHeight=wrapper.clientHeight
//根据包装的大小计算图像大小(占视口的百分比)。
//例如,如果包装是视口的40%,则图像将是视口的160%
让imageHeight=200-((包装器高度/视口)*100)
//设置新的图像高度
imgObj.style.height=图像高度+“vh”
正文{
填充:0;
保证金:0;
}
.container{}
.图像包装器{
位置:相对位置;
溢出:隐藏;
宽度:100vw;
高度:100vh;
}
.图像内容{
位置:绝对位置;
}
#形象{
背景:蓝色;
}

您可能只需要使用css就可以实现这一点,但是在这种情况下,我更愿意使用css+js,因为它将为您提供一些细粒度的控制。您可以设置所需的maxImageWidth、maxClientWidth、maxClientHeight和minClientWidth,而不会导致图像在浮动div内跳转。I节流调整大小
事件:

!function(){
  var img = document.getElementsByTagName("img")[0],
      maxImageWidth  = 4000,
      maxClientWidth = 2000,
      maxClientHeight  = 1000,
      minClientWidth = 200;

  window.addEventListener("resize",function(e){
    if(img._busy){return}
    img._busy = true;
    window.requestAnimationFrame(function(){
      adjust();
      img._busy = false;
    })
  });

  function adjust(){
    if(!img._ratio){
      var rect = img.getBoundingClientRect();
      img._ratio = rect.height/rect.width;
    }
    var w = document.documentElement.clientWidth,
        currentImageWidth = maxImageWidth * (1 - Math.max(0,Math.min(1,(w - minClientWidth)/(maxClientWidth - minClientWidth))));
    img.style.width = currentImageWidth + "px";
    var currentImageHeight = currentImageWidth * img._ratio;
    img.style.marginTop = -Math.max(0,(currentImageHeight - maxClientHeight)/2) + "px";
  };


  adjust();
}();
另外,不要忘记在img上添加
最小高度:100%
最小宽度:100%
。 请参见此
在evergreen浏览器+ie11上测试。

非常感谢。你的回答帮助了我。