如何动态改变CSS样式?

omvjsjqw  于 2023-01-27  发布在  其他
关注(0)|答案(4)|浏览(118)

我有一个简单的元素:

<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

kmbjn2e3

kmbjn2e31#

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

f5emj3cl2#

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

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

2lpgd968

2lpgd9683#

[2023年]查看此Stackblitz snippet
就像这样:

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

piv4azn74#

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

相关问题