拖拽平移与缩放图片时,如何隐藏超出容器的部分?
解决图片拖拽缩放时超出容器无法隐藏的问题
我要实现图片拖拽、平移、缩放功能,同时让超出容器的图片部分被隐藏。目前用的结构和样式如下:
HTML代码
<div class="region-device-images-modal"> <img id="device_model_image" src="{src}"> </div>
初始CSS
.region-device-images-modal { height: 100%; width: 100%; display: flex; justify-content: center; align-items: center; overflow: hidden; cursor: pointer; } .region-device-images-modal>img { max-width: 100%; max-height: 100%; }
初始加载时图片能正常居中显示,但当拖拽/缩放时给图片加上这些样式后:
transform: scale(4); position: absolute; left: -127.25px; top: -1111.59px;
容器的overflow:hidden就不管用了,超出容器的图片部分会露出来,我需要让这部分被隐藏。
解决方法
问题根源是绝对定位的参考对象不对:当图片设为position:absolute,如果父容器没有设置非static的定位(比如relative),图片会以视口或者上层的定位元素为基准,这时候父容器的overflow:hidden约束不到它。
只需要给父容器加一行position:relative就行:
.region-device-images-modal { height: 100%; width: 100%; display: flex; justify-content: center; align-items: center; overflow: hidden; cursor: pointer; position: relative; /* 新增这行 */ }
加了之后,图片的绝对定位会以父容器为基准,父容器的overflow:hidden就能正常裁剪超出的部分了,而且初始的flex居中布局也不会受影响,拖拽缩放的功能依然正常工作。
内容的提问来源于stack exchange,提问作者Nate
相关产品推荐
相关产品推荐

