原文链接: 仿京东搜索框
上一篇: 14 个js 问题
下一篇: 相对定位 和 绝对 定位的比较
使用子绝父相的布局方法,仿照京东的搜索框
看起来也还行,把相机换为了清除的按钮
绝对定位方式,脱离文档流,不会占用页面空间。以最近的不是static定位的父级元素作为参考进行定位,如果其所有的父级元素都是static定位,那么此元素最终则是以当前窗口作为参考进行定位。可以使用top,bottom,left,right进行位置移动,亦可使用z-index在z轴上面进行移动。当元素为此定位时,如果该元素为内联元素,则会变为块级元素,即可以直接设置其宽和高的值;如果该元素为块级元素,则其宽度会由初始的100%变为auto。
相对定位方式,相对于其父级元素(无论父级元素此时为何种定位方式)进行定位,准确地说是相对于其父级元素所剩余的未被占用的空间进行定位(在父元素由多个相对定位的子元素时可以看出),且会占用该元素在文档中初始的页面空间,即在使用top,bottom,left,right进行移动位置之后依旧不会改变其所占用空间的位置。可以使用z-index进行在z轴方向上的移动。
子绝父相布局,设置父元素为绝对定位,然后设置子元素为相对定位,设置top,left,bottom,right,等值来放置子组件,可以为负值
<template>
<div class="form">
<div class="input">
<input type="text" v-model="text">
<div class="close" v-show="showClose" @click="close"/>
</div>
<div class="search"></div>
</div>
</template>
<script>
export default {
name: "close-input",
data() {
return {
text: '',
}
},
computed: {
showClose() {
return this.text.length != 0
},
},
methods: {
close() {
this.text = ''
}
}
}
</script>
<style scoped>
.form {
display: flex;
position: relative;
height: 30px;
width: fit-content;
}
.input {
position: relative;
}
.close {
display: flex;
position: absolute;
height: 30px;
width: 30px;
right: 0;
bottom: 0;
background: url("/static/close.png");
background-size: cover;
}
.search {
position: absolute;
right: -30px;
bottom: 0;
height: 30px;
width: 30px;
border: 0;
padding: 3px;
background: url("/static/search1.png");
background-color: red;
background-size: cover;
}
</style>