用js实现元素两个元素位置对齐

一、问题描述

使得填表单位那一行字与下面的表格左对齐,对表格使用css中的margin:auto实现了居中,但是对那一行字(用div包裹的)使用margin:auto不生效;并且2021年下面对应的月份是动态变化的,月份的个数不定;

二、解决方案

(1)把那行字放在表格里,再把这行表格的边框去掉;

(2)固定表格的宽度;2021年的列固定宽度,下面对应的月份的宽度按均分配;

(3)使用原生js前端操作dom,计算出外边距;

三、实现

 1   mounted() {  2      const tag=document.getElementsByClassName("tg")[0 ]  3      let margin_value=window.getComputedStyle(tag, null  ).marginLeft  4   console.log(tag)  5      console.log(window.getComputedStyle(tag, null  ).marginLeft)  6      const value=document.getElementsByClassName("custom-title")[0 ]  7   console.log(value)  8      value.setAttribute("style","margin-left:"+ margin_value)  9    },

解释:“tg”为表格的类名,获取表格的外边距的值;“custom-title”为那一行字所在元素的类名;给那行字的标签添加style属性,赋值即可。

四、效果

 

标签: Javascript

添加新评论