生活随笔
收集整理的這篇文章主要介紹了
vue自定义指令截取图片中心显示
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用vue做項目時,有一種產品需求,是像朋友圈一樣展示圖片,在小圖時,只展示中心的一部分圖片
在vue中可以用自定義指令來做
<div class=
"image-item" v-for=
"(image, index) in data.img" :key=
"index"><img v-interceptImg :src=
"image.img_min" alt=
"">
</div>
復制代碼.image-item {width: 100%;height: 100%;
float: left;display: flex;overflow: hidden;align-items: center;justify-content: center;
}
復制代碼export function interceptImg (el, binding) {el.addEventListener(
'load', () => {
let width = el.naturalWidth;
let height = el.naturalHeight;// 獲取父元素的設定寬度
let parentWidth = Number(window.getComputedStyle(el.parentNode).width.replace(
'px',
''));
let parentHeight = Number(window.getComputedStyle(el.parentNode).height.replace(
'px',
''));// 獲取父元素寬高比例
let scale = binding.value ? binding.value.scale : parentHeight / parentWidth;// 清除元素style值el.style =
'';
if (height / width < scale) {el.style.height =
'100%';// 獲取圖片放入后實際的寬度//
let imgWidth = Number(window.getComputedStyle(el).width.replace(
'px',
''));
let imgWidth = (width * parentHeight) / height;el.style.marginLeft = `
${(parentWidth - imgWidth) / 2}px`;}
else if (height / width > scale) {el.style.width =
'100%';}
else {el.style.width =
'100%';el.style.height =
'100%';}});
}
復制代碼
總結
以上是生活随笔為你收集整理的vue自定义指令截取图片中心显示的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。