2. 设置图片的方式有很多种 可以通过背景图来设置background;在项目中一些小图片建议使用字体图标代替?
<
template>
<
div
class=
"hello">
<
div
class=
"dom_width">
<
img
class=
"img_block"
v-for="(item, index)
in listImg"
:key="index"
:src="item"
alt=
"">
div>
div>
template>
<
script>
export
default {
name
:
"HelloWorld",
data() {
return {
listImg
: [
"https://desk-fd.zol-img.com.cn/t_s720x360c5/g5/M00/0D/06/ChMkJlojp_qITurJAAuxrJdcGiEAAiwQAKU7i0AC7HE992.jpg",
"https://desk-fd.zol-img.com.cn/t_s720x360c5/g5/M00/03/00/ChMkJ1pcn7OIULOjAAWUOFboVoEAAkG3ANBKU8ABZRQ309.jpg",
"https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1046983545,2051560208&fm=27&gp=0.jpg"
]
}
},
created() {
},
mounted() {
// 获取所有的img标签
let imgList
= document.
querySelectorAll(
".img_block");
// 获取父元素宽高
let parentWh
= imgList[
0].parentNode;
let wid
=
this.
getWidHei(parentWh,
'width');
let hei
=
this.
getWidHei(parentWh,
'height');
// 等比压缩图片
this.
AutoSize(imgList, wid, hei);
},
methods
: {
AutoSize(
listImg,
maxWidth,
maxHeight) {
//原图片原始地址(用于获取原图片的真实宽高,当标签指定了宽、高时不受影响)
let image
=
new
Image();
for (
let i
=
0; i
< listImg.length; i
++) {
// 获取每一个图片的宽高
image.src
= listImg[i].src;
// 当图片比图片框小时不做任何改变
if (image.width
< maxWidth
&& image.height
< maxHeight) {
//原图片宽高比例 大于 图片框宽高比例
listImg[i].width
= image.width;
listImg[i].height
= image.height;
}
else {
//原图片宽高比例 大于 图片框宽高比例,则以框的宽为标准缩放,反之以框的高为标准缩放
if (maxWidth
/ maxHeight
<= image.width
/ image.height) {
listImg[i].width
= maxWidth;
//以框的宽度为标准
listImg[i].height
= maxWidth
* (image.height
/ image.width);
}
else {
listImg[i].width
= maxHeight
* (image.width
/ image.height);
listImg[i].height
= maxHeight;
//以框的高度为标准
}
}
}
},
// 考虑 IE 的兼容性
getStyle(
el) {
if (window.getComputedStyle) {
return window.
getComputedStyle(el,
null);
}
else {
return el.currentStyle;
}
},
// 通过当前元素获取宽高
getWidHei(
el,
name) {
let val
= name
===
"width"
? el.offsetWidth
: el.offsetHeight,
which
= name
===
"width"
? [
"Left",
"Right"]
: [
"Top",
"Bottom"];
// display is none
if (val
===
0) {
return
0;
}
let style
=
this.
getStyle(el);
// 左右或上下两边的都减去
for (
let i
=
0, a; (a
= which[i
++]); ) {
val
-=
parseFloat(style[
"border"
+ a
+
"Width"])
||
0;
val
-=
parseFloat(style[
"padding"
+ a])
||
0;
}
return val;
}
}
};
script>
<
style
scoped>
.dom_width {
width:
200
px;
height:
300
px;
background-color:
skyblue;
}
style>