aboutsummaryrefslogtreecommitdiff
path: root/files/ru/web/api/window/getcomputedstyle/index.html
blob: 85080b7fa747c53c3d5206c73b5b12e59947b7ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
---
title: window.getComputedStyle()
slug: Web/API/Window/getComputedStyle
translation_of: Web/API/Window/getComputedStyle
---
<p class="summary"><span class="seoSummary">Метод <strong><code>Window.getComputedStyle()</code></strong> возвращает объект, содержащий значения всех CSS-свойств элемента, полученных после применения всех активных таблиц стилей, и завершения базовых вычислений значений, которые они могут содержать.</span> Некоторые CSS-свойства доступны через API, предоставляемые объектом, или индексацию по именам CSS-свойств.</p>

<h2 id="Синтаксис">Синтаксис</h2>

<pre class="syntaxbox">var <em>style</em> = window.getComputedStyle(<em>element</em> [, <em>pseudoElt</em>]);
</pre>

<dl>
 <dt><code>element</code></dt>
 <dd>{{domxref("Element")}}, свойства которого необходимо получить.</dd>
 <dt><code>pseudoElt</code> {{optional_inline}}</dt>
 <dd>Строка указывающая на найденный псевдо-элемент. Опускается (или <code>null</code>) для не псевдо-элементов.</dd>
</dl>

<p>Возвращенный <code>style</code> живой {{domxref("CSSStyleDeclaration")}} объект, который обновляется автоматически когда элемент стилей изменяется.</p>

<h2 id="Выводы">Выводы</h2>

<p>Метод <code>Window.getComputedStyle()</code> предоставляет все значения CSS свойств элементов после применения текущей таблицы стилей или базового расчета каких-либо значений, которые могут быть.</p>

<h2 id="Пример">Пример</h2>

<pre class="brush: js">var elem1 = document.getElementById("elemId");
var style = window.getComputedStyle(elem1, null);

// this is equivalent:
// var style = document.defaultView.getComputedStyle(elem1, null);
</pre>

<pre class="brush: js">&lt;style&gt;
 #elem-container{
   position: absolute;
   left:     100px;
   top:      200px;
   height:   100px;
 }
&lt;/style&gt;

&lt;div id="elem-container"&gt;dummy&lt;/div&gt;
&lt;div id="output"&gt;&lt;/div&gt;

&lt;script&gt;
  function getTheStyle(){
    var elem = document.getElementById("elem-container");
    var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("height");
    document.getElementById("output").innerHTML = theCSSprop;
   }
  getTheStyle();
&lt;/script&gt;
</pre>

<pre class="brush: js">function dumpComputedStyles(elem,prop) {

  var cs = window.getComputedStyle(elem,null);
  if (prop) {
    console.log(prop+" : "+cs.getPropertyValue(prop));
    return;
  }
  var len = cs.length;
  for (var i=0;i&lt;len;i++) {

    var style = cs[i];
    console.log(style+" : "+cs.getPropertyValue(style));
  }

}
</pre>

<h2 id="Описание">Описание</h2>

<p>Возвращенный объект - это такой же объект, который возвращается из свойства элемента {{domxref("HTMLElement.style", "style")}}; Так или иначе, эти два объекта имеют разные назначения. Объект который возвращается из <code>getComputedStyle</code> только для чтения и может быть использован для инспектирования стиля элемента (включая описание из <code>&lt;style&gt;</code> элемента или внешней таблицы стилей). Объект <code>element.style</code> следует использовать для установки стилей на специфических элементах.</p>

<p>Первый аргумент должен быть элементом (вставка узлов которые не являются элементами, например <code>#text</code> выдаст ошибку).</p>

<h2 id="defaultView"><code>defaultView</code></h2>

<p>Во многих примерах кода, <code>getComputedStyle</code> используется из объекта <code>document.defaultView</code>. Почти во всех случаях это не нужно, поскольку <code>getComputedStyle</code> существует в объекте <code>window</code>. Это что-то на подобии шаблона defaultView который был некой прослойкой. Люди не хотели писать спецификацию для <code>window</code> и создавали <code>API</code>  которое также могло использоваться для Java. Так или иначе <a class="link-https" href="https://github.com/jquery/jquery/pull/524#issuecomment-2241183" title="https://github.com/jquery/jquery/pull/524#issuecomment-2241183">есть только один случай</a> когда метод <code>defaultView</code> должен использоваться: когда вы используете Firefox 3.6 чтобы получить доступ к вычисленным стилям.</p>

<h2 id="Использования_с_псевдо-элементами">Использования с псевдо-элементами</h2>

<p><code>getComputedStyle</code> может получить информацию о стилях из псевдо-элемента (например - <code>::after</code>, <code>::before</code>, <code>::marker</code>, <code>::line-marker</code> - <a class="external" href="https://www.w3.org/TR/css-pseudo-4/">спецификация</a>).</p>

<pre class="brush: html">&lt;style&gt;
 h3::after {
   content: 'rocks!';
 }
&lt;/style&gt;

&lt;h3&gt;generated content&lt;/h3&gt;

&lt;script&gt;
  var h3 = document.querySelector('h3');
  var result = getComputedStyle(h3, ':after').content;

  console.log('the generated content is: ', result); // возвратит 'rocks!'
&lt;/script&gt;
</pre>

<h2 id="Notes">Notes</h2>

<p>The values returned by <code>getComputedStyle</code> are known as {{cssxref("resolved_value", "resolved values")}}. These are usually the same as the CSS 2.1 {{cssxref("computed_value","computed values")}}, but for some older properties like <code>width</code>, <code>height</code> or <code>padding</code>, they are instead the {{cssxref("used_value","used values")}}. Originally, CSS 2.0 defined the computed values to be the "ready to be used" final values of properties after cascading and inheritance, but CSS 2.1 redefined computed values as pre-layout, and used values as post-layout. For CSS 2.0 properties, the <code>getComputedStyle</code> function returns the old meaning of computed values, now called <strong>used values</strong>. An example of difference between pre- and post-layout values includes the resolution of percentages that represent the width or the height of an element (also known as its layout), as those will be replaced by their pixel equivalent only in the used value case.</p>

<p>The returned value is, in certain known cases, expressly inaccurate by deliberate intent. In particular, to avoid the so called CSS History Leak security issue, browsers may expressly "lie" about the used value for a link and always return values as if a user has never visited the linked site. See <a class="external" href="http://blog.mozilla.com/security/2010/03/31/plugging-the-css-history-leak/">http://blog.mozilla.com/security/2010/03/31/plugging-the-css-history-leak/</a> and <a class="external" href="http://hacks.mozilla.org/2010/03/privacy-related-changes-coming-to-css-vistited/">http://hacks.mozilla.org/2010/03/privacy-related-changes-coming-to-css-vistited/</a> for details of the examples of how this is implemented. Most other modern browsers have applied similar changes to the application of pseudo-selector styles and the values returned by <code>getComputedStyle</code>.</p>

<p>During a CSS transition, <code>getComputedStyle</code> returns the original property value in Firefox, but the final property value in WebKit.</p>

<p>In Firefox, properties with the value <code>auto</code> return the used value, not the value <code>auto</code>. So if you apply <code>top:auto;</code> and <code>bottom:0</code>; on an element with <code>height:30px</code> and its containing block is <code>height:100px;</code>, upon requesting the computed style for <code>top</code>, Firefox will return <code>top:70px</code>, as <code>100px-30px=70px</code>.</p>

<h2 id="Браузерная_поддержка">Браузерная поддержка</h2>

<p>{{CompatibilityTable}}</p>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Edge</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>9</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
  <tr>
   <td>pseudo-element support</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>9</td>
   <td>15</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Edge</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>WP7 Mango</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
  <tr>
   <td>pseudo-element support</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<h2 id="Спецификации">Спецификации</h2>

<ul>
 <li><a class="external" href="https://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSview-getComputedStyle">DOM Level 2 Style: getComputedStyle</a></li>
 <li><a href="https://drafts.csswg.org/cssom/#dom-window-getcomputedstyle" title="https://drafts.csswg.org/cssom/#dom-window-getcomputedstyle">CSS Object Model specification</a></li>
</ul>

<h2 id="See_also" name="See_also">Смотреть также</h2>

<ul>
 <li>{{domxref("window.getDefaultComputedStyle")}}</li>
 <li>{{cssxref("resolved_value", "Resolved Value")}}</li>
</ul>