第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 的尺寸。

浙公网安备 33010602011771号