繁体   English   中英

如何动态更改 CSS 样式?

[英]How to dynamically change CSS style?

我有简单的元素:

<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>

如何仅动态更改nav-indexnav-up

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

请注意,根据thisthisnav-indexnav-up仅受 Opera 支持。

像这样:

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;
}

创建一个新的 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.
}

您可以使用 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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM