html自定义弹窗实现图片高度自适应

实际效果:
点击

实现

再次点击则弹窗消失。
弹窗布局为:

<div class="box">
<img class="img" id="img" src=""/>
</div>

css样式为:

.box {
position: fixed;
left: 0;
top: 0;
bottom: 0;
right: 0;
background: rgba(0, 0, 0, .3);
overflow: auto;
display: none;
}
.box img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
max-width: 100%;
/*max-height: 100%;*/
}

要求是图片居中,宽度为100%,如果图片过长时,图片显示纵向滚动条,问题是图片过长时有滚动条,但是无法翻到顶部。
解决办法:用js控制图片的动态定位。
相似例子代码为(项目本身使用vue,下面代码为html+css+js模拟项目实现的效果):

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title>sdfsd</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
html,body {
width: 100%;
height: 100%;
}
.showImg{
width: 100px;
height: 100px;
}
.box {
position: fixed;
left: 0;
top: 0;
bottom: 0;
right: 0;
background: rgba(0, 0, 0, .3);
overflow: auto;
}
.box {
display: none;
}
.box img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
max-width: 100%;
/*max-height: 100%;*/
}
</style>
</head>
<body>
<!--宽图片-->
<img class="showImg" onclick="clickImg('https://img.zcool.cn/community/019489590ad530a801214550df4b17.jpg@2o.jpg')" src="https://img.zcool.cn/community/019489590ad530a801214550df4b17.jpg@2o.jpg"/>
<!--长图片-->
<img class="showImg" onclick="clickImg('http://img.redocn.com/sheji/20180206/chaochangshujiabangongshiyixiangtu_9149371.jpg')" src="http://img.redocn.com/sheji/20180206/chaochangshujiabangongshiyixiangtu_9149371.jpg"/>

<div class="box">
<img class="img" id="img" src=""/>
</div>
<script type="text/javascript">
function clickImg(url){
console.log(url);
$(".box #img").attr('src',url);
var image = new Image();
image.src = url;
let realHei = image.height;//图片的实际高度
let clientHei = post.body.clientHeight;//屏幕高度
let setHei = '50%';
if(clientHei*2<realHei){
//我本身用的是((realHei - clientHei*2)/732)*2*100;移动端的要根据实际用的缩放来看
let heiPercent = ((realHei - clientHei*2)/732)*100;
setHei = (50+heiPercent) + '%';
}
$(".box").css('display','block');
$(".img").css('top',setHei);
}

$(".box").click(function(){
$(this).css('display','none');
});
</script>
</body>
</html>

但是在保持图片比例不变的前提下,加上max-height: 100%;实现图片过长时,宽度自适应更方便有效。
记录一下,回头有空看看能不能不用js动态控制定位,仅用css实现这种效果。
———————
版权声明:本文为CSDN博主「zuo-yiran」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zuoyiran520081/article/details/80598843

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享