深入解析:如何使用 JavaScript 获取 HTML 元素的样式和属性
知止自律打卡-微信小程序APP
一款微信自律打卡小程序,支持自定义打卡项目、习惯记录、项目日记、专注计时与数据统计。自律打卡、学习打卡、读书打卡、健身打卡、运动打卡、减肥打卡、戒色打卡、养生打卡、戒烟、戒酒、戒熬夜等多种场景。万能打卡模板自由创建。可自定义每日打卡目标,记录习惯连续天数,可视化追踪成长进度。
了解产品详情 →
微信搜索「知止自律打卡」
1 前言
在前端开发中,操作 HTML 元素的样式与属性是常见的任务,无论是动态调整页面样式,还是获取元素属性进行逻辑判断,都需要熟练掌握相关技巧。JavaScript 提供了丰富的 API,允许开发者轻松获取和修改 HTML 元素的样式与属性,从而实现动态和交互式的网页效果。
本篇文章将详细讲解如何使用 JavaScript 获取 HTML 元素的样式和属性,并结合实际案例帮助您快速上手,提升开发效率。无论您是前端新手还是资深开发者,都可以从中找到实用的技巧和灵感。
2 基础样式代码
<style>
button {
/* 超出按钮部分隐藏 */
overflow: hidden;
/* padding 撑开按钮 */
/*padding: 4vmin 8vmin;*/
padding: 5px 10px;
/* 去掉按钮边框、给个圆角 */
border: none;
border-radius: 10vmin;
/* 按钮的渐变背景颜色 */
background-image: linear-gradient(90deg, #0acffe, #495aff);
/* 文字颜色、大小、粗细、字间距 */
color: #fff;
font-size: 55px;
font-weight: bold;
letter-spacing: 1vmin;
/* 鼠标小手 */
cursor: pointer;
width: 200px;
position: relative;
}
</style>
<button id="btn">按钮</button>

3 js提取属性案例
<script>
/**
* 有勇气的牛排
* 获取指定id元素的所有样式,并以字典形式返回
* @param {string} elementId - 元素的id
* @returns {Object | null} - 返回样式字典,如果元素不存在,返回null
*/
function getAllStylesById(elementId) {
// 获取指定id的元素
let element = document.getElementById(elementId);
console.log("999")
console.log(element)
// 检查元素是否存在
if (element == null) {
element = document.getElementsByTagName(elementId)
console.log(element)
}
if (!element) {
// console.warn(`Element with id "${elementId}" not found.`);
return null;
}
// 获取元素的计算样式
const computedStyle = window.getComputedStyle(element);
const styles = {};
const styles2 = {};
// 将所有样式属性及其值添加到字典中
for (let i = 0; i < computedStyle.length; i++) {
const property = computedStyle[i];
styles2[property] = computedStyle.getPropertyValue(property);
}
console.log(styles2);
// 获取元素的边界矩形
const rect = element.getBoundingClientRect();
styles["url"] = "https://www.couragesteak.com/"
styles["width"] = computedStyle.getPropertyValue("width")
styles["height"] = computedStyle.getPropertyValue("height")
styles["backgroundColor"] = computedStyle.getPropertyValue("background-color")
styles["backgroundImage"] = computedStyle.getPropertyValue("background-image")
styles["color"] = computedStyle.getPropertyValue("color")
styles["bottom"] = computedStyle.getPropertyValue("bottom")
styles["top"] = computedStyle.getPropertyValue("top")
styles["left"] = computedStyle.getPropertyValue("left")
styles["right"] = computedStyle.getPropertyValue("right")
// 位置
styles["position"] = {
top: rect.top + window.scrollY, // 相对于页面顶部的绝对位置
left: rect.left + window.scrollX, // 相对于页面左侧的绝对位置
bottom: rect.bottom + window.scrollY, // 相对于页面底部的绝对位置
right: rect.right + window.scrollX // 相对于页面右侧的绝对位置
}
return styles;
}
// 案例
const styles = getAllStylesById("btn");
console.log("js获取button样式");
console.log(styles);
</script>

标签: