2017-08-26 81 views
0

我的网页上有动态内容,并带有一些特征图像。在大屏幕上,图像漂浮在页面的右侧,在小屏幕上,我将图像作为块处理,并将其宽度设置为屏幕的100%。使图像尽可能大,即使它需要拉伸更大

这对大多数图像来说已经足够好用了,但有时图像非常高,这使得在小图片上显示图片占屏幕宽度的100%很困难,而且您可能需要滚动一段时间才能过去图片。

为了解决这个问题,我为图像设置了最大高度,并且在第一个图像背后有一个模糊的副本,这个副本是100%宽度以填充虚空。 (有点像电视台以一种分辨率播放并以不同分辨率播放视频时所做的。

它的效果很好,除非我想让图像尽可能大,无论是100%宽度还是达到最大高度。对于小图像,它只是和实际图像的尺寸一样大。

figure{position:relative;overflow:hidden;float:right;width:202px;margin:0 0 0.5rem 0.5rem;font-size:0;text-align:center} 
figure img{margin:auto;max-width:100%;max-height:400px;width:auto;height:auto;display:block;border:0} 
figure span{display:block;position:absolute;z-index:-1;filter:blur(10px);-ms-filter:blur(10px);filter:progid:DXImageTransform.Microsoft.Blur(PixelRadius='10');top:-10px;left:-10px;padding:10px;width:100%;height:100%} 
figcaption{text-align:left;background:#fff;font-size:0.75rem} 

@media(max-width:528px){ 
figure{float:none;margin:0 auto;width:100%} 
figure img{max-height:300px}} 

<figure> 
<a href="#"><img src="dynamicPic.jpg"> 
<span style="background:url(dynamicPic.jpg) no-repeat center;background-size:cover"></span> 
</a> 
<figcaption>Dynamic Caption</figcaption> 
</figure> 

回答

0

我认为JavaScript的一个有点可以做的伎俩

var img = document.getElementById("image-id-here"); 
img.onload = function(){ 
    var maxWidth = (document.body.clientHeight/img.height) * img.width; 
    var maxHeight = (document.body.clientWidth/img.width) * img.height; 
    if(maxWidth > document.body.clientWidth){ 
     img.width = img.width * (maxHeight/img.height); 
     img.height = maxHeight; 
    }else{ 
     img.width = maxWidth 
     img.height = img.height * (maxWidth/img.width); 
    } 
} 

这应该图像尺寸调整到最大尺寸,但仍保持纵横比。

重要提示:上面的代码应在图片标签加载后运行