2012-02-25 65 views
1

我有简单的元素:如何动态改变CSS风格?

<a id="a1" href="#" style="position:absolute;top:0 ;left:0 ;nav-index:1;nav-down:#b1;nav-right:#a3;nav-left:#a1;nav-up:#a1">A1</a> 

如何只dynamicaly改变资产净值指数和NAV-吗?

+2

是否可以将这些内联样式移动到单独的样式表中? – biziclop 2012-02-25 13:05:17

回答

3

像这样:

var a1 = document.getElementById('a1'); 
a1.style['nav-index'] = /* somevalue */; 
a1.style['nav-up'] = /* somevalue */; 
// or (style properties with hypens must be converted 
// to a camel case representation for use in 'dot notation') 
a1.style.navIndex = /* somevalue */; 
a1.style.navUp = /* somevalue */; 
// and to retrieve the original values: 
a1.style['nav-index'] = ''; 
a1.style['nav-up'] = ''; 

而且它的最好的内联样式移动到一个类中的CSS文件。

.a1nav { 
position:absolute; 
top:0; 
left:0; 
nav-index:1; 
nav-down:#b1; 
nav-right:#a3; 
nav-left:#a1; 
nav-up:#a1; 
} 
4
document.getElementById('a1').style.navIndex = newIndex; 
document.getElementById('a1').style.navUp = newValue; 

注意,按照thisthisnav-indexnav-up只被Opera支持。

+0

我已经更新了答案。 – check123 2012-02-25 13:10:09

0

创建一个新的CSS和使用这样

function changeClass (elementID, newClass) { 
    var element = document.getElementById(elementID); 

    element.setAttribute("class", newClass); //For Most Browsers 
    element.setAttribute("className", newClass); //For IE; harmless to other browsers. 
} 
-1

您可以使用jQuery来改变导航索引和导航式调用它们。

$('a#a1').attr('nav-index', '2'); //If you want to change it to 2. 
$('a#a1').attr('nav-up', '#5'); //If you want to change it to #5.