Модифицируем CSS свойства через JavaScript

Представляю Вашему вниманию универсальный метод для манипулирования CSS свойствами в Javascript сценариях. Протестировано во всех современных браузерах (включая IE6).

Вы можете спросить меня: а зачем это нужно, если есть CSS? Ну например, для создания анимации какого-либо элемента при определенном событии или вам нужно узнать значение свойства элемента. У меня год назад был один проект, где через систему управления для разных разделов подгружались флешки разной высоты и необходимо было для элемента <div> прописать эту высоту. Просчет высоты осуществлял PHP и подставлял ее значение в простой JS сценарий.

Таблица соответствия CSS свойств Javascript аналогам:

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
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
float styleFloat
text-align textAlign
text-decoration textDecoration
text-decoration: blink textDecorationBlink
text-decoration: line-through textDecorationLineThrough
text-decoration: none textDecorationNone
text-decoration: overline textDecorationOverline
text-decoration: underline textDecorationUnderline
text-indent textIndent
text-transform textTransform
top top
vertical-align verticalAlign
visibility visibility
width width
z-index zIndex

Пример использования:

function $() {
var elements = new Array();

for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element);

if (arguments.length == 1)
return element;

elements.push(element);
}

return elements;
}

//После загрузки страницы
window.onload = function() {
//установим блоку с id=mydiv высоту 95px
//ВНИМАНИЕ! не забывайте указывать px или pt
$(‘mydiv’).style.height=’95px’;

//выведем значение ширины блока mydiv
alert($(‘mydiv’).style.width);
}

Вы наверняка обратили внимание на функцию $() я ее взял из библиотеки Prototype, чтобы не использовать каждый раз getElementById.

h++p://www.webmagazine.biz/articles/css_properties_to_javascript_conversion.html

Оставьте первый комментарий

Оставить комментарий

Ваш электронный адрес не будет опубликован.


*


пять × 2 =