如何动态更改css样式?

时间:2012-02-25 13:01:54

标签: javascript 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>

如何仅动态更改导航索引和导航?

4 个答案:

答案 0 :(得分:4)

document.getElementById('a1').style.navIndex = newIndex;
document.getElementById('a1').style.navUp = newValue;

请注意,根据thisthis,只有Opera支持nav-indexnav-up

答案 1 :(得分: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;
}

答案 2 :(得分: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.
}

答案 3 :(得分:-1)

您可以使用jquery更改nav-index和nav-up。

$('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.