简体   繁体   English

用 JavaScript 得到一个 CSS 的值

[英]Get a CSS value with JavaScript

I know I can set a CSS value through JavaScript such as:我知道我可以通过 JavaScript设置一个 CSS 值,例如:

document.getElementById('image_1').style.top = '100px';

But, can I get a current specific style value?但是,我可以获得当前特定样式值吗? I've read where I can get the entire style for the element, but I don't want to have to parse the whole string if I don't have to.我已经阅读了在哪里可以获得元素的整个样式,但如果不需要的话,我不想解析整个字符串。

You can use getComputedStyle() .您可以使用getComputedStyle()

 var element = document.getElementById('image_1'), style = window.getComputedStyle(element), top = style.getPropertyValue('top'); console.log(top);
 <img id="image_1">

jsFiddle . js小提琴

The element.style property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style. element.style 属性让您知道只有 CSS 在该元素中定义为内联的属性(以编程方式,或在元素的样式属性中定义),您应该获得计算样式。

Is not so easy to do it in a cross-browser way, IE has its own way, through the element.currentStyle property, and the DOM Level 2 standard way, implemented by other browsers is through the document.defaultView.getComputedStyle method.以跨浏览器的方式做到这一点并不容易,IE 有自己的方式,通过 element.currentStyle 属性,而其他浏览器实现的 DOM Level 2 标准方式是通过 document.defaultView.getComputedStyle 方法。

The two ways have differences, for example, the IE element.currentStyle property expect that you access the CSS property names composed of two or more words in camelCase (eg maxHeight, fontSize, backgroundColor, etc), the standard way expects the properties with the words separated with dashes (eg max-height, font-size, background-color, etc).两种方式有区别,例如,IE element.currentStyle 属性期望您访问的属性名称由两个或多个驼峰命名的单词组成(例如 maxHeight、fontSize、backgroundColor 等),标准方式期望属性具有用破折号分隔的单词(例如最大高度、字体大小、背景颜色等)。 ...... ……

function getStyle(el, styleProp) {
    var value, defaultView = (el.ownerDocument || document).defaultView;
    // W3C standard way:
    if (defaultView && defaultView.getComputedStyle) {
        // sanitize property name to css notation
        // (hyphen separated words eg. font-Size)
        styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
        return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
    } else if (el.currentStyle) { // IE
        // sanitize property name to camelCase
        styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
            return letter.toUpperCase();
        });
        value = el.currentStyle[styleProp];
        // convert other units to pixels on IE
        if (/^\d+(em|pt|%|ex)?$/i.test(value)) { 
            return (function(value) {
                var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
                el.runtimeStyle.left = el.currentStyle.left;
                el.style.left = value || 0;
                value = el.style.pixelLeft + "px";
                el.style.left = oldLeft;
                el.runtimeStyle.left = oldRsLeft;
                return value;
            })(value);
        }
        return value;
    }
}

Main reference stackoverflow 主要参考stackoverflow

Use the following.使用以下内容。 It helped me.它帮助了我。

document.getElementById('image_1').offsetTop

See also Get Styles .另请参阅获取 Styles

Cross-browser solution to checking CSS values without DOM manipulation:在没有 DOM 操作的情况下检查 CSS 值的跨浏览器解决方案:

function get_style_rule_value(selector, style)
{
 for (var i = 0; i < document.styleSheets.length; i++)
 {
  var mysheet = document.styleSheets[i];
  var myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;

  for (var j = 0; j < myrules.length; j++)
  {
   if (myrules[j].selectorText && myrules[j].selectorText.toLowerCase() === selector)
   {
    return myrules[j].style[style];
   }
  }
 }
};

Usage:用法:

get_style_rule_value('.chart-color', 'backgroundColor')

Sanitized version (forces selector input to lowercase, and allows for use case without leading ".")消毒版本(强制选择器输入为小写,并允许不带前导“.”的用例)

function get_style_rule_value(selector, style)
{
 var selector_compare=selector.toLowerCase();
 var selector_compare2= selector_compare.substr(0,1)==='.' ?  selector_compare.substr(1) : '.'+selector_compare;

 for (var i = 0; i < document.styleSheets.length; i++)
 {
  var mysheet = document.styleSheets[i];
  var myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;

  for (var j = 0; j < myrules.length; j++)
  {
    if (myrules[j].selectorText)
    {
     var check = myrules[j].selectorText.toLowerCase();
     switch (check)
     {
      case selector_compare  :
      case selector_compare2 : return myrules[j].style[style];
     }
    }
   }
  }
 }

If you set it programmatically you can just call it like a variable (ie document.getElementById('image_1').style.top ).如果您以编程方式设置它,您可以像调用变量一样调用它(即document.getElementById('image_1').style.top )。 Otherwise, you can always use jQuery:否则,您始终可以使用 jQuery:

<html>
    <body>
        <div id="test" style="height: 100px;">Test</div>
        <script type="text/javascript" src="jquery.min.js"></script>
        <script type="text/javascript">
            alert($("#test").css("height"));
        </script>
    </body>
</html>

In 2021 2021年

check before use使用前检查

You can use computedStyleMap()您可以使用computedStyleMap()

The answer is valid but sometimes you need to check what unit it returns, you can get that without any slice() or substring() string.答案是有效的,但有时您需要检查它返回的单位是什么,您可以在没有任何slice()substring()字符串的情况下获得它。

var element = document.querySelector('.js-header-rep');
element.computedStyleMap().get('padding-left');

 var element = document.querySelector('.jsCSS'); var con = element.computedStyleMap().get('padding-left'); console.log(con);
 .jsCSS { width: 10rem; height: 10rem; background-color: skyblue; padding-left: 10px; }
 <div class="jsCSS"></div>

I know I can set a CSS value through JavaScript such as:我知道我可以通过 JavaScript设置CSS 值,例如:

document.getElementById('image_1').style.top = '100px';

But, can I get a current specific style value?但是,我可以获得当前特定的样式值吗? I've read where I can get the entire style for the element, but I don't want to have to parse the whole string if I don't have to.我已经阅读了在哪里可以获得元素的整个样式,但是如果我不需要,我不想解析整个字符串。

The cross-browser solution without DOM manipulation given above does not work because it gives the first matching rule, not the last.上面给出的没有 DOM 操作的跨浏览器解决方案不起作用,因为它给出了第一个匹配规则,而不是最后一个。 The last matching rule is the one which applies.最后一个匹配规则是适用的。 Here is a working version:这是一个工作版本:

function getStyleRuleValue(style, selector) {
  let value = null;
  for (let i = 0; i < document.styleSheets.length; i++) {
    const mysheet = document.styleSheets[i];
    const myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
    for (let j = 0; j < myrules.length; j++) {
      if (myrules[j].selectorText && 
          myrules[j].selectorText.toLowerCase() === selector) {
        value =  myrules[j].style[style];
      }
    }
  }
  return value;
}  

However, this simple search will not work in case of complex selectors.但是,这种简单的搜索在复杂选择器的情况下将不起作用。

As a matter of safety, you may wish to check that the element exists before you attempt to read from it.为安全起见,您可能希望在尝试读取元素之前检查该元素是否存在。 If it doesn't exist, your code will throw an exception, which will stop execution on the rest of your JavaScript and potentially display an error message to the user -- not good.如果它不存在,您的代码将抛出异常,这将停止在 JavaScript 的 rest 上执行,并可能向用户显示一条错误消息——不好。 You want to be able to fail gracefully.你希望能够优雅地失败。

var height, width, top, margin, item;
item = document.getElementById( "image_1" );
if( item ) {
  height = item.style.height;
  width = item.style.width;
  top = item.style.top;
  margin = item.style.margin;
} else {
  // Fail gracefully here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM