js实现jq .css

实现 jQuery 的 .css() 方法
在原生 JavaScript 中,可以通过操作 DOM 元素的 style 属性或 getComputedStyle 方法来模拟 jQuery 的 .css() 功能。以下是几种常见场景的实现方式:
获取样式值
function getStyle(element, property) {
return window.getComputedStyle(element).getPropertyValue(property);
}
// 使用示例
const div = document.querySelector('div');
const color = getStyle(div, 'color');
设置单个样式属性
function setStyle(element, property, value) {
element.style[property] = value;
}
// 使用示例
const div = document.querySelector('div');
setStyle(div, 'color', 'red');
设置多个样式属性
function setStyles(element, styles) {
for (const property in styles) {
element.style[property] = styles[property];
}
}
// 使用示例
const div = document.querySelector('div');
setStyles(div, {
color: 'red',
backgroundColor: '#fff',
fontSize: '16px'
});
链式调用实现
function css(element, property, value) {
if (typeof property === 'object') {
for (const prop in property) {
element.style[prop] = property[prop];
}
} else if (value === undefined) {
return window.getComputedStyle(element).getPropertyValue(property);
} else {
element.style[property] = value;
}
return element;
}
// 使用示例
const div = document.querySelector('div');
// 获取样式
const color = css(div, 'color');
// 设置单个样式
css(div, 'color', 'blue');
// 设置多个样式
css(div, {
color: 'red',
background: 'yellow'
});
// 链式调用
css(div, 'color', 'green').css(div, 'fontSize', '20px');
注意事项
- 使用
getComputedStyle获取的是最终计算值,包括浏览器默认样式 - 设置样式时,属性名可以使用驼峰式(如
backgroundColor)或短横线式(如background-color) - 对于需要带单位的数值(如
width、height),需要手动添加单位 - 修改内联样式会覆盖外部样式表中的规则
这些方法组合起来可以基本实现 jQuery .css() 方法的核心功能,包括获取样式、设置单个或多个样式属性,以及支持链式调用。







