Название документа

Свойство style

Свойство style представляет глобальный атрибут style HTML-элемента. Значением свойства style является объект CSSStyleDeclaration, который содержит всю стилевую информацию HTML-элемента, добавленную в элемент через глобальный атрибут style. Свойствами объекта CSSStyleDeclaration являются CSS свойства.

Для изменения или добавления новых стилей к HTML-элементу нужно воспользоваться свойством, имя которого будет совпадать с именем CSS свойства, значение которого вы хотите изменить. Например, чтобы вывести текстовое содержимое элемента курсивным шрифтом красного цвета, можно выполнить следующие инструкции:

elem.style.fontStyle = "italic"; elem.style.color = "red";

Обратите внимание, что все значения свойств объекта CSSStyleDeclaration должны задаваться в виде строк. Например, в таблице стилей или атрибуте style можно написать:

color: red; font-size: 50px; text-decoration: underline;

Чтобы сделать тоже самое в JavaScript необходимо заключить все значения в кавычки:

elem.style.color = "red"; elem.style.fontSize = "50px"; elem.style.textDecoration = "underline";

Обратите внимание, что точки с запятыми не входят в строковые значения. Точки с запятой, используемые в CSS, не нужны в строковых значениях, устанавливаемых с помощью JavaScript.

Многие свойства CSS, такие как text-decoration, содержат в своих именах дефис. В JavaScript дефис интерпретируется как оператор минус, поэтому инструкция, приведённая ниже, не будет работать:

elem.style.text-decoration = "overline";

Таким образом, имена свойств объекта CSSStyleDeclaration немного отличаются от имён реальных CSS-свойств. Если имя CSS свойства содержит дефисы, то имя свойства объекта CSSStyleDeclaration образуется путём удаления всех дефисов и перевода в верхний регистр буквы, непосредственно следующей за каждым из дефисов. Например CSS-свойство list-style-type в JavaScript будет выглядеть как listStyleType.

Читайте также:  Появилась горизонтальная прокрутка html

Кроме того, когда CSS свойство, такое как float, имеет имя, совпадающее с зарезервированным словом языка JavaScript, к этому имени добавляется префикс «css», чтобы создать допустимое имя свойства. То есть, чтобы прочитать или изменить значение CSS-свойства float, следует использовать свойство cssFloat.

При использовании свойств объекта CSSStyleDeclaration для чтения стилевой информации о HTML-элементе осмысленную информацию будут возвращать только те свойства, значения для которых были ранее установлены сценарием или заданы с помощью атрибута style.

Встроенный стиль элемента в JavaScript удобно использовать только для установки стилей. Для получения стилевой информации элемента (значения всех CSS-свойств установленных для элемента) нужно использовать метод window.getComputedStyle().

Пример

      

Это абзац.

Копирование материалов с данного сайта возможно только с разрешения администрации сайта
и при указании прямой активной ссылки на источник.
2011 – 2023 © puzzleweb.ru

Источник

Style textDecoration Property

The textDecoration property sets or returns one ore more decorations for a text.

Tip: To specify more than one decoration type for an element, specify a space separated list of decoration types.

Browser Support

Syntax

Return the textDecoration property:

Set the textDecoration property:

Property Values

Value Description
none Defines a normal text. This is default
underline Defines a line under the text
overline Defines a line over the text
line-through Defines a line through the text
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

Technical Details

Default Value: none
Return Value: A String, representing the decoration added to the text
CSS Version CSS1

More Examples

Example

Return the text decoration of an element:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

How to set the style of the line in a text decoration with JavaScript?

In this tutorial, we shall learn to set the style of the line in a text decoration with JavaScript. To set the style of the line in JavaScript, use the textDecorationStyle property. You can set underline, double, or overline, etc. for the line style. Let us discuss our topic in brief.

Using the Style textDecorationStyle Property

We can set or return the line style in a text decoration with this property.

The major browsers support this property. Firefox adds support with an alternate property named MozTextDecorationStyle.

Syntax

Following is the syntax to set the style of the line in a text decoration using the JavaScript Style textDecorationStyle property −

object.style.textDecorationStyle = solid | double | dotted | dashed | wavy | initial |inherit;

With this syntax, the required text-decoration line style can be set to the element’s style.

Parameters

  • solid − Single line display.
  • double − A double line.
  • dotted − A dotted line.
  • dashed − A dashed line.
  • wavy − A wavy line
  • initial − Sets this property to its default value.
  • inherit − Inherits this property from its parent element.

The default value of this property is solid. The return value is a string representing the text-decoration line style.

Example 1

You can try to run the following code to return the style of the line in a text-decoration with JavaScript −

!DOCTYPE html> html> body> div id="myText" style="text-decoration: underline;"> This is demo text. /div> br> button onclick="display()"> Set Text Decoration /button> script> function display() document.getElementById("myText") .style.textDecorationColor="red"; document.getElementById("myText") .style.textDecorationStyle="double"; > /script> /body> /html>

Example 2

In this program, we are setting the text-decoration line style to the content of the div element.

We get the text-decoration line style from the user. The style inherit will display the text-decoration line style set to the parent element of our content. In this program, this style is set as dashed.

When the user ticks on the button, we call the function to set the text-decoration line style following the syntax given above.

!DOCTYPE html> html> head> style> #txtDecStylEl text-decoration: underline; > #txtDecStylParent text-decoration-style: dashed; > /style> /head> body> h3> Setting the style of text-decoration line using the i> textDecorationStyle /i> property /h3> div id="txtDecStylParent"> div id="txtDecStylEl"> Set the text-decoration line style here. /div> /div> br> div id="txtDecStylBtnWrap"> select id="txtDecStylSel" size="10"> option/> dotted option/> dashed option/> double option selected="selected"/> solid option/> wavy option/> initial option/> inherit /select> br> p> Select the text-decoration line style and click on the button./p> button onclick="setTextDecLineStyle();"> Apply /button> /div> br> /body> script> function setTextDecLineStyle() var txtDecStylSelTag=document.getElementById("txtDecStylSel"); var txtDecStylSelIndx=txtDecStylSelTag.selectedIndex; var txtDecStylSelStat=txtDecStylSelTag.options[txtDecStylSelIndx].text; var txtDecStylBtnWrap=document.getElementById("txtDecStylBtnWrap"); var txtDecStylUsrEl=document.getElementById("txtDecStylEl"); txtDecStylUsrEl.style.textDecorationStyle=txtDecStylSelStat;//Firefox browser txtDecStylUsrEl.style.MozTextDecorationStyle=txtDecStylSelStat; txtDecStylUsrEl.innerHTML="You have set the text-decoration line style to b>" + txtDecStylUsrEl.style.textDecorationStyle + ""; > /script> /html>

Example 3

This program has set the text-decoration line style to the content inside a div element. We display the text-decoration line style to the user when they click on the button following the syntax for getting the style of the text-decoration line.

html> head> style> #txtDecStylGetEl text-decoration: underline; > /style> /head> body> h3>Getting the style of the text-decoration line using the i> textDecorationStyle /i>property. /h3> div id="txtDecStylGetEl" style="text-decoration-style: dashed"> Get the text-decoration line style of this content. /div> br> div id="txtDecStylGetBtnWrap"> p> Click on the button to get the style./p> button onclick="getTextDecStyle();">Get/button> /div> br> p id="txtDecStylGetOp"> /p> /body> script> function getTextDecStyle() var txtDecStylGetBtnWrap=document.getElementById("txtDecStylGetBtnWrap"); var txtDecStylGetEl=document.getElementById("txtDecStylGetEl"); var txtDecStylGetOp=document.getElementById("txtDecStylGetOp"); txtDecStylGetOp.innerHTML="The text-decoration line style is token operator">+ txtDecStylGetEl.style.textDecorationStyle; > /script> /html>

In this tutorial, we went through the textDecorationStyle property in JavaScript. To set the style of the text-decoration line, this property is a built-in property in JavaScript and very easy to code.

Источник

Style textDecorationStyle Property

The textDecorationStyle property sets or returns how the line, if any, will display.

Browser Support

Syntax

Return the textDecorationStyle property:

Set the textDecorationStyle property:

Property Values

Value Description
solid Default value. The line will display as a single line
double The line will display as a double line
dotted The line will display as a dotted line
dashed The line will display as a dashed line
wavy The line will display as a wavy line
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

Technical Details

Default Value: solid
Return Value: A String, representing the text-decoration-style property of an element
CSS Version CSS3

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

textDecoration style property

Specifies or returns the appearance characteristics of text, whether it is underlined, overlined, lined-through or blinking text.

You can specify a space separated list of decoration types, if you want to use more than one for an element.

Syntax:

Possible values:

Description of values:

Use default anchor decoration.
The text content of the element blinks.
Takes the value of this property from the computed style of the parent element.
The text content of the element is displayed with a line through the middle.
No text decoration is used.
The text content of the element is displayed with a line at the top.
The text content of the element is underlined.

Example HTML code 1:

head> style> .example  text-decoration: overline line-through; > style> head> body> a class="example">Text decoration: overline line-throughp> body>

Example HTML code 2:

head> script type="text/javascript"> function ChangeTextDecoration (elem)  var anchor = document.getElementById ("myAnchor"); var checkboxes = document.getElementsByName ("checkboxs"); var decorValue = ""; // Checks all checkbox state for (var i = 0; i < checkboxes.length; i++)  if (checkboxes[i].checked) < decorValue += checkboxes[i].value + " "; > > // If none is checked all other checked out var noneCh = document.getElementsByName("nonecheck"); if (noneCh[0].checked)  for (var i = 0; i < checkboxes.length; i++) < checkboxes[i].checked = false; > decorValue = "none"; > anchor.style.textDecoration = decorValue; > script> head> body> a id="myAnchor">Text decoration samplea> br />br /> Change text-decoration value: br /> input type="checkbox" name="checkboxs" value="blink" onclick="ChangeTextDecoration ();"/>blinkbr /> input type="checkbox" name="checkboxs" value="line-through" onclick="ChangeTextDecoration ();"/>line-throughbr /> input type="checkbox" name="checkboxs" value="overline" onclick="ChangeTextDecoration ();"/>overlinebr /> input type="checkbox" name="checkboxs" value="underline" onclick="ChangeTextDecoration ();"/>underlinebr /> input type="checkbox" name="nonecheck" onclick="ChangeTextDecoration ();" />none body>

Supported by objects:

Источник

Оцените статью