如何使用原生JavaScript获取元素当前生效的transform属性值
解决方案
问题原因
直接使用.style.transform只能读取元素行内style属性中设置的样式,你写在CSS文件、媒体查询中的样式属于浏览器最终渲染的计算后样式,无法通过style属性直接获取。
实现方法
方法1:通过计算样式自动解析(适配任意动态样式规则)
通过window.getComputedStyle拿到元素最终生效的transform属性(矩阵格式),再结合元素高度换算得到百分比值:
// 获取目标元素 const footerEl = document.getElementById('footer-div'); // 读取元素最终计算样式 const computedStyle = window.getComputedStyle(footerEl); const transformVal = computedStyle.transform; if (transformVal === 'none') { console.log('当前未设置transform属性'); } else { // 解析矩阵字符串,提取Y轴偏移的像素值 const matrixParams = transformVal.match(/matrix.*\((.+)\)/)[1].split(', '); const offsetYpx = Number(matrixParams[5]); // 结合元素高度换算为百分比 const percentVal = Math.round(Math.abs(offsetYpx / footerEl.offsetHeight * 100)) + '%'; console.log(percentVal); // 输出93% / 89% } // 如需监听视口变化自动更新值,添加resize监听即可 window.addEventListener('resize', () => { // 重新执行上述计算逻辑 })
方法2:匹配媒体查询直接取值(适合规则固定的场景)
如果你的媒体查询规则不会频繁修改,可以直接通过window.matchMedia判断当前命中的规则,直接取对应值,逻辑更简单:
let translateYPercent; if (window.matchMedia('(min-width: 472px)').matches) { translateYPercent = '89%'; } else if (window.matchMedia('(min-width: 287px)').matches) { translateYPercent = '93%'; } console.log(translateYPercent);
内容的提问来源于stack exchange,提问作者User1548789
相关产品推荐
相关产品推荐

