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