- Javascript DOM Style borderLeft Property
- Browser Compatibility
- Syntax
- Property Values
- Default Value
- Return Value
- More Examples
- Example
- Related
- .style
- Как пишется
- Как понять
- На практике
- Саша Беспоясов советует
- Style borderLeft Property
- Browser Support
- Syntax
- Property Values
- Technical Details
- More Examples
- Example
- Example
- Related Pages
- COLOR PICKER
- HOW TO
- SHARE
- CERTIFICATES
- Report Error
- Thank You For Helping Us!
- Top Tutorials
- Top References
- Top Examples
- Web Certificates
Javascript DOM Style borderLeft Property
The borderLeft property gets and sets up to three separate border-left properties, in a shorthand form.
With this property, you can set/return one or more of the following in any order:
Browser Compatibility
Syntax
Return the borderLeft property:
let a = object.style.borderLeft;
Set the borderLeft property:
object.style.borderLeft = "width style color|initial|inherit"
Property Values
Parameter width style color initial inherit | Description the width of the left border the style of the left border the color of the left border this property to its default value. Inherits this property from its parent element. |
---|
Default Value
Return Value
A String, representing the width, style and/or color of the left border of an element.
More Examples
Change the width, style and color of the left border of a element:
document.getElementById("myDiv").style.borderLeft = "thin dotted red";
!DOCTYPE html> html> head> style> #myDiv !-- w w w . d e m o 2 s. c om --> border: thick solid blue; > body> div id="myDiv">This is a div element. br> button type="button" onclick="myFunction()">Change left border script> function myFunction() < document.getElementById("myDiv").style.borderLeft = "thin dotted red"; >
Example
Return the border-left property values of a element:
document.getElementById('demo').innerHTML = document.getElementById("myDiv").style.borderLeft;
!DOCTYPE html> html> body> div id="myDiv" style="border-left:5px solid red;">This is a div element. br> button type="button" onclick="myFunction()">Return left border p id='demo'> script> function myFunction() < document.getElementById('demo').innerHTML = document.getElementById("myDiv").style.borderLeft; >
Related
- Javascript DOM Style borderImageSlice Property
- Javascript DOM Style borderImageSource Property
- Javascript DOM Style borderImageWidth Property
- Javascript DOM Style borderLeft Property
- Javascript DOM Style borderLeftColor Property
- Javascript DOM Style borderLeftStyle Property
- Javascript DOM Style borderLeftWidth Property
demo2s.com | Email: | Demo Source and Support. All rights reserved.
.style
Свойство style получает и устанавливает инлайновые стили элемента, то есть те, что записываются через HTML-атрибут style .
С помощью него можно управлять стилем элемента. Специфичность этого свойства такая же, как у атрибута style .
Как пишется
Скопировать ссылку «Как пишется» Скопировано
Чтобы получить значения инлайновых стилей с помощью свойства style , мы можем записать:
const element = document.getElementById('someElement')const inlineStyles = element.style
const element = document.getElementById('someElement') const inlineStyles = element.style
В этом случае в значение inline Styles запишется объект CSS Style Declaration , который будет содержать в себе все инлайновые стили элемента element .
Чтобы задать стили для элемента, мы можем использовать несколько способов. Либо через css Text , чтобы указать несколько свойств разом. (Тем же эффектом обладает установка стиля через set Attribute ( ) .) Либо через отдельные свойства в style . [ property Name ] .
Следующие две записи работают одинаково и устанавливают несколько стилей в одном выражении:
element.style.cssText = 'color: blue; border: 1px solid black'element.setAttribute('style', 'color:red; border: 1px solid blue;')
element.style.cssText = 'color: blue; border: 1px solid black' element.setAttribute('style', 'color:red; border: 1px solid blue;')
Следующая — устанавливает значение определённого свойства, оставляя другие значения стиля нетронутыми:
element.style.color = 'blue'
element.style.color = 'blue'
Как понять
Скопировать ссылку «Как понять» Скопировано
Свойство style — это механизм для работы со стилями на элементе. С его помощью можно управлять отображением элементов в «рантайме», то есть во время выполнения скрипта.
Этот механизм позволяет «перетирать» стили, описанные в CSS-таблицах, так как специфичность стилей в атрибуте style выше (за исключением стилей с !important ).
Чтобы указать значение конкретного CSS-свойства, мы можем использовать одноимённое отображение в style :
// Если мы хотим указать color:element.style.color = 'red' // или 'rgb(255,0,0)', или '#f00' // Если хотим указать font-family:element.style.fontFamily = 'Arial'
// Если мы хотим указать color: element.style.color = 'red' // или 'rgb(255,0,0)', или '#f00' // Если хотим указать font-family: element.style.fontFamily = 'Arial'
Обратите внимание, что имена свойств в style . [ property Name ] записываются в camelCase, в отличие от CSS-свойств, которые записываются через дефис.
Таким образом font — family превращается в font Family , а, например, background — color — в background Color .
При сомнениях в том, как правильно называется то или иное свойство, воспользуйтесь списком соответствий:
CSS | JavaScript |
---|---|
background | background |
background-attachment | backgroundAttachment |
background-color | backgroundColor |
background-image | backgroundImage |
background-position | backgroundPosition |
background-repeat | backgroundRepeat |
border | border |
border-bottom | borderBottom |
border-bottom-color | borderBottomColor |
border-bottom-style | borderBottomStyle |
border-bottom-width | borderBottomWidth |
border-color | borderColor |
border-left | borderLeft |
border-left-color | borderLeftColor |
border-left-style | borderLeftStyle |
border-left-width | borderLeftWidth |
border-right | borderRight |
border-right-color | borderRightColor |
border-right-style | borderRightStyle |
border-right-width | borderRightWidth |
border-style | borderStyle |
border-top | borderTop |
border-top-color | borderTopColor |
border-top-style | borderTopStyle |
border-top-width | borderTopWidth |
border-width | borderWidth |
clear | clear |
clip | clip |
color | color |
cursor | cursor |
display | display |
filter | filter |
float | cssFloat |
font | font |
font-family | fontFamily |
font-size | fontSize |
font-variant | fontVariant |
font-weight | fontWeight |
height | height |
left | left |
letter-spacing | letterSpacing |
line-height | lineHeight |
list-style | listStyle |
list-style-image | listStyleImage |
list-style-position | listStylePosition |
list-style-type | listStyleType |
margin | margin |
margin-bottom | marginBottom |
margin-left | marginLeft |
margin-right | marginRight |
margin-top | marginTop |
overflow | overflow |
padding | padding |
padding-bottom | paddingBottom |
padding-left | paddingLeft |
padding-right | paddingRight |
padding-top | paddingTop |
page-break-after | pageBreakAfter |
page-break-before | pageBreakBefore |
position | position |
stroke-dasharray | strokeDasharray |
stroke-dashoffset | strokeDashoffset |
stroke-width | strokeWidth |
text-align | textAlign |
text-decoration | textDecoration |
text-indent | textIndent |
text-transform | textTransform |
top | top |
vertical-align | verticalAlign |
visibility | visibility |
width | width |
На практике
Скопировать ссылку «На практике» Скопировано
Саша Беспоясов советует
Скопировать ссылку «Саша Беспоясов советует» Скопировано
В целом для управления стилями лучше использовать CSS. Можно использовать классы-модификаторы, чтобы придавать какие-то наборы стилей элементу.
Инлайновые стили имеют более высокую специфичность — их труднее переопределить, и это мешает нормальной работе со стилями элемента.
Пример. Мы пишем библиотеку, которая умеет красиво рисовать кнопки. Если мы установим цвет и размер кнопки с помощью инлайновых стилей, то пользователь библиотеки не сможет их легко поменять. Использовать такую библиотеку никто не захочет
Однако есть некоторые случаи, когда манипуляция инлайн-стилями — это ок. Например, если мы хотим управлять отображением элемента точечно, и описывать это в CSS невозможно.
Представьте, что вы хотите сделать анимацию движения точки на экране так, чтобы движение было случайным. В CSS (пока что) этого сделать нельзя, только скриптами. И вот здесь изменение инлайновых стилей как раз кстати.
Для изменения таких стилей используется свойство style .
Используйте style , чтобы изменить или получить инлайновые стили элемента.
🛠 Чтобы переписать стиль элемента полностью, можно использовать css Text или set Attribute .
element.style.cssText = 'color: blue; border: 1px solid black'element.setAttribute('style', 'color:red; border: 1px solid blue;')
element.style.cssText = 'color: blue; border: 1px solid black' element.setAttribute('style', 'color:red; border: 1px solid blue;')
🛠 Чтобы обновить значение конкретного свойства, а остальные оставить нетронутыми, используйте style . [ property Name ] :
element.style.color = 'red'element.style.fontFamily = 'Arial'
element.style.color = 'red' element.style.fontFamily = 'Arial'
🛠 Чтобы сбросить значение, присвойте ему null .
// Если у элемента прописано style="background-color: red; color: black;",// то такая запись:element.style.backgroundColor = null // . оставит только style="color: black;".
// Если у элемента прописано style="background-color: red; color: black;", // то такая запись: element.style.backgroundColor = null // . оставит только style="color: black;".
🛠 Численным свойствам, таким как margin , padding , border — width и другим, следует указывать не только значение, но и единицу измерения:
element.style.marginTop = '50px'
element.style.marginTop = '50px'
Style borderLeft Property
The borderLeft property sets or returns up to three separate border-left properties, in a shorthand form.
With this property, you can set/return one or more of the following (in any order):
Browser Support
The borderLeft property is supported in all major browsers.
Syntax
Return the borderLeft property:
Set the borderLeft property:
Property Values
Parameter | Description |
---|---|
width | Sets the width of the left border |
style | Sets the style of the left border |
color | Sets the color of the left border |
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: | not specified |
---|---|
Return Value: | A String, representing the width, style and/or color of the left border of an element |
CSS Version | CSS1 |
More Examples
Example
Change the width, style and color of the left border of a element:
Example
Return the border-left property values of a element:
Related Pages
COLOR PICKER
HOW TO
SHARE
CERTIFICATES
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
Web Certificates
W3Schools is optimized for learning, testing, and training. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy. Copyright 1999-2020 by Refsnes Data. All Rights Reserved.
Powered by W3.CSS.