写一个获取非行间样式的方法

获取非行间样式,也就是计算样式,可以使用 JavaScript 的 window.getComputedStyle() 方法。 这个方法返回一个包含元素所有计算样式的 CSSStyleDeclaration 对象。

以下是一个示例函数,它接受一个元素和一个 CSS 属性名作为参数,并返回该元素的计算样式值:

function getComputedStyleValue(element, propertyName) {
  if (!element || !propertyName) {
    return undefined; // 处理无效输入
  }

  const computedStyles = window.getComputedStyle(element);
  return computedStyles.getPropertyValue(propertyName);
}


// 示例用法:
const myElement = document.getElementById('myElement'); // 获取元素
const backgroundColor = getComputedStyleValue(myElement, 'background-color'); // 获取背景颜色
const fontSize = getComputedStyleValue(myElement, 'font-size'); // 获取字体大小

console.log("Background Color:", backgroundColor);
console.log("Font Size:", fontSize);


// 处理伪元素样式 (::before, ::after)
function getPseudoElementStyleValue(element, pseudoElementSelector, propertyName) {
  if (!element || !pseudoElementSelector || !propertyName) {
    return undefined;
  }
  const computedStyles = window.getComputedStyle(element, pseudoElementSelector);
  return computedStyles.getPropertyValue(propertyName);
}

const contentBefore = getPseudoElementStyleValue(myElement, '::before', 'content');
console.log("Content of ::before:", contentBefore);


//  更简洁的写法 (如果确定元素存在)
const element = document.querySelector('#myElement');
const computedBackgroundColor = getComputedStyle(element).backgroundColor;
const computedFontSize = getComputedStyle(element).fontSize; // 或  getComputedStyle(element).getPropertyValue('font-size');

console.log("Background Color (shorter version):", computedBackgroundColor);
console.log("Font Size (shorter version):", computedFontSize);


关键点:

  • window.getComputedStyle(element, pseudoElt): 这是核心方法。 element 是你想要获取样式的元素。 pseudoElt 是可选参数,用于获取伪元素(例如 ::before::after)的样式。 如果不指定,则获取元素本身的样式。
  • getPropertyValue(propertyName): 这个方法用于获取特定 CSS 属性的值。 propertyName 应该是 CSS 属性名的小写形式(例如 'background-color','font-size',而不是 'backgroundColor' 或 'fontSize')。 它返回一个字符串值。
  • 返回值: 函数返回一个字符串,表示计算样式的值。 例如,rgb(255, 0, 0)16px
  • 错误处理: 上面的代码包含了简单的错误处理,以防止在传入无效参数时出现错误。
  • 单位: 返回值包含单位 (例如 'px', 'em', 'rem', '%')。 如果需要数值进行计算,需要解析字符串并提取数值。

这个改进的版本更简洁,包含了错误处理,并演示了如何获取伪元素的样式。 记住,getComputedStyle 获取的是最终应用到元素上的样式,包括来自样式表、继承和默认样式。

posted @ 2024-12-06 06:23  王铁柱6  阅读(27)  评论(0)    收藏  举报