第146篇:响应式动态居中(js+css,vue)
好家伙,
1.使用js原生
<div id="container" style="position: relative; width: 100%; height: 100vh;">
<div id="hero" style="position: relative;"></div>
</div>
<script>
const hero = document.getElementById('hero');
const container = document.getElementById('container');
hero.style.width = '100px';
hero.style.height = '100px';
hero.style.background = '#ffcc00';
window.onload = function () {
function update() {
let heroX = hero.clientWidth;
let heroY = hero.clientHeight;
let containerX = container.clientWidth;
let containerY = container.clientHeight;
hero.style.left = (containerX - heroX) / 2 + 'px';
hero.style.top = (containerY - heroY) / 2 + 'px';
}
update();
window.addEventListener('resize', update);
}
</script>
-
window.onload
: 当整个页面及其资源(包括图片、脚本、样式等)加载完成时,会执行onload
内的代码。 -
update
函数:heroX
和heroY
分别获取hero
元素的当前宽度和高度。containerX
和containerY
分别获取container
元素的当前宽度和高度。hero.style.left
和hero.style.top
分别设置hero
的水平和垂直位置,通过计算将其居中。公式(containerX - heroX) / 2
计算出hero
左边缘到container
左边缘的距离,使hero
水平居中,类似地,(containerY - heroY) / 2
计算出hero
上边缘到container
上边缘的距离,使其垂直居中。
-
update();
: 初始调用update
函数,确保页面加载时hero
元素被正确居中。 -
window.addEventListener('resize', update);
: 添加窗口大小变化事件的监听器,每当浏览器窗口尺寸发生变化时,update
函数会被再次调用,重新计算并更新hero
的位置,确保它始终在container
中居中。
2.vue
在vue中使用计算属性实现
<template>
<div :style="containerStyle">
<div ref="content" :style="contentStyle">
动态居中的内容
</div>
</div>
</template>
<script>
export default {
data() {
return {
containerWidth: 0,
containerHeight: 0,
contentWidth: 0,
contentHeight: 0,
};
},
mounted() {
// 在组件挂载时,获取容器和内容的尺寸
this.updateDimensions();
window.addEventListener('resize', this.updateDimensions);
},
beforeDestroy() {
window.removeEventListener('resize', this.updateDimensions);
},
computed: {
containerStyle() {
return {
position: 'relative',
width: '100%',
height: '100vh',
};
},
contentStyle() {
return {
position: 'absolute',
top: `${(this.containerHeight - this.contentHeight) / 2}px`,
left: `${(this.containerWidth - this.contentWidth) / 2}px`,
backgroundColor: 'lightblue',
padding: '20px',
};
},
},
methods: {
updateDimensions() {
// 更新容器的宽度和高度
this.containerWidth = this.$el.clientWidth;
this.containerHeight = this.$el.clientHeight;
// 更新内容的宽度和高度
const contentEl = this.$refs.content;
this.contentWidth = contentEl.clientWidth;
this.contentHeight = contentEl.clientHeight;
},
},
};
</script>
<style scoped>
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
</style>
通过计算属性计算出位置
获取并更新容器的宽度和高度,使用 this.$el.clientWidth
和 this.$el.clientHeight
获取 container
的尺寸。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步