(忽略图大小不一致,一般UI给的图会刚好适合页面大小,我这网上找的图,难调大小,我行内的就自己随便写的宽高),另外悄悄告诉你最后有简单方法~~
先来看看初始DOM结构代码
<template>
<div id="app">
<div class="bodyy">
<div class="grandparent">
<div class="parent">
<img class="imgClass" style="width: 320px; height:120px" src="https://img0.baidu.com/it/u=2190700831,1994064510&fm=253&fmt=auto&app=138&f=JPEG?w=667&h=500">
</div>
<div class="brother1">222</div>
<div class="brother2">333</div>
<div>5555</div>
</div>
</div>
</div>
</template>
最开始图片在他本来的DOM结构里面,爷爷也没有背景,这样的DOM是把两个叔叔抵下去的
假设我们已经固定了图片为孙子,但是我们想要这个图片作为整个爷爷的背景图,想要其他该在爷爷上边的元素的层级不变,也就是这样的DOM结构:
效果是这样
话不多说,直接上代码:(这里要通过img的class获取爷爷元素,所以用v-show当满足某种条件才渲染这种我需要的样式,倘若知道爷爷元素和图片的大小直接v-if
<template>
<div id="app">
<div class="bodyy">
<div class="grandparent">
<div class="parent">
<img class="imgClass" v-show="a != 1" src="https://img2.baidu.com/it/u=443161650,959310912&fm=253&fmt=auto&app=138&f=JPEG?w=888&h=500">
</div>
<div class="brother1">222</div>
<div class="brother2">333</div>
</div>
</div>
</div>
</template>
<script>
import SlotDemo from '@/views/slotDemo/index.vue'
export default {
name: 'App',
data() {
return {
a: 1
}
},
components: {
SlotDemo
},
mounted() {
if(this.a == 1) {
console.log('000000')
this.showImg()
}
},
methods: {
showImg() {
// 获取到当前 <img> 元素
// var imgElement = document.querySelector('img');
var imgElement = document.getElementsByClassName('imgClass')
console.log('999', imgElement.width, imgElement.height, typeof(imgElement.height + 'px'))
let numm = imgElement.height + 'px'
console.log('numm', numm)
// 获取当前 <img> 元素的父元素的父元素
var grandParentElement = imgElement[0].parentElement.parentElement;
console.log('grandParentElement', grandParentElement)
// 设置父元素的父元素的背景图
grandParentElement.style.backgroundImage = `url('https://img0.baidu.com/it/u=2190700831,1994064510&fm=253&fmt=auto&app=138&f=JPEG?w=667&h=500')`;
grandParentElement.style.backgroundSize = 'cover'; // 设置背景图片的尺寸适应父元素大小
grandParentElement.style.height = numm;
},
}
}
</script>
<style >
*{
margin: 0;
padding: 0;
}
.bodyy{
background: #798866;
z-index: 8888;
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
.grandparent{
width: 100%;
height: auto;
position: absolute;
bottom: 0;
min-height: 3.5rem;
background: #ffffff;
border-top-left-radius: 0.48rem;
border-top-right-radius: 0.48rem;
.parent{
background: blue;
img{
}
}
.brother1{
//background: white;
position: relative;
height: auto;
margin-top: 15rem;
}
.brother2{
display: flex;
flex-direction: column;
align-content: center;
justify-content: center;
margin-top: 0.36rem;
margin-bottom: 0.68rem;
width: 100%;
height: auto;
position: relative;
}
}
}
</style>
TIPS:有个简单单方案就是直接给parent加一个margin-bottom!!