How Can I Get the Computed Font Size of a DOM Element in JavaScript?

Mary-Kate Olsen
Release: 2024-11-22 02:51:19
Original
736 people have browsed it

How Can I Get the Computed Font Size of a DOM Element in JavaScript?

Obtaining Computed Font Size in DOM Elements Using JavaScript

Determining the actual font size applied to a DOM element, considering inherited and global settings, can be a common task in web development. This is especially useful when working with plugins or automating tasks that require accurate font size information.

Generic Approach for Computed Font Size Detection

To achieve framework-independent font size retrieval, you can leverage the following approach:

function getStyle(el, styleProp) {
  // Convert property name to camelCase for IE compatibility
  let camelize = (str) => str.replace(/\-(\w)/g, s => s[1].toUpperCase());

  // Attempt IE's non-standard currentStyle
  if (el.currentStyle) {
    return el.currentStyle[camelize(styleProp)];
  }
  // Try DOM Level 2 getComputedStyle if available
  else if (document.defaultView && document.defaultView.getComputedStyle) {
    return document.defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
  }
  // Fallback to inline style
  else {
    return el.style[camelize(styleProp)];
  }
}
Copy after login

Usage:

const element = document.getElementById('elementId');
const fontSize = getStyle(element, 'font-size');
Copy after login

By using this approach, you can obtain the computed font size for any DOM element, regardless of its inheritance or global settings.

The above is the detailed content of How Can I Get the Computed Font Size of a DOM Element in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template