我有这个HTML
<div id="slideMenu">
<div id="slideM1" onmouseover="colorM(1)">Something 1</div>
<div id="slideM2" onmouseover="colorM(2)">Something 2</div>
<div id="slideM3" onmouseover="colorM(3)">Something 3</div>
<div id="slideM4" onmouseover="colorM(4)">Something 4</div>
<div id="slideM5" onmouseover="colorM(5)">Something 5</div>
</div>
和这个CSS
html, body{
font-family: "Century Gothic", "Apple Gothic", AppleGothic, "URW Gothic L", "Avant Garde", Futura, sans-serif;
}
#slideMenu {
float: right;
}
#slideM1:before, #slideM2:before, #slideM3:before, #slideM4:before, #slideM5:before {
content: "";
position: absolute;
top:0;
right:210px;
width: 0;
height: 0;
border-top: 32px solid transparent;
border-right: 30px solid #602F4F;
border-bottom: 32px solid transparent;
display:none;
}
#slideM1, #slideM2, #slideM3, #slideM4, #slideM5 {
background-color: silver;
height: 54px;
width: 200px;
text-align: right;
position:relative;
padding: 5px;
color: white;
margin-bottom: 2px;
}
最后这个Javascript
function colorM(n) {
document.getElementById("slideM"+n).style.backgroundColor="#602F4F";
document.getElementById("slideM"+n+":before").style.display="block";
}
这是jsfiddle http://jsfiddle.net/xN6Da/。如您所见,CSS三角形的默认值为display: none;
。但在它徘徊之后,我想改变它的价值才能看得见。我尝试使用document.getElementById("slideM"+n+":before").style.display="block";
,但它仍然隐藏了三角形,那么如何使用Javascript从CSS中删除display: none;
?
谢谢
答案 0 :(得分:2)
您无法通过Javascript修改伪类。您需要通过添加/删除类来更改它。例如,通过添加这样的CSS:
#slideM1.show:before, #slideM2.show:before, #slideM3.show:before, #slideM4.show:before, #slideM5.show:before {
display: block;
}
和这个Javascript
function colorM(n) {
document.getElementById("slideM"+n).style.backgroundColor="#602F4F";
document.getElementById("slideM"+n+).className="show";
}
这是小提琴。 http://jsfiddle.net/xN6Da/1/
我建议删除ID并用普通类替换它们。目前,每次添加另一个元素。您将需要创建另一个ID并将其添加到CSS。
答案 1 :(得分:-1)
如果您询问如何通过Javascript更改样式规则,这是我使用的代码:
//* Function: putClassAttrib((myclass,myatt,myval)
//* Purpose: Add/modify a rule in a given class
putClassAttrib = function(myclass,myatt,myval) {
// e.g. putClassAttrib(".hideme","whiteSpace","nowrap")
var myrules;
if (document.all) {
myrules = 'rules';
}
else if (document.getElementById) {
myrules = 'cssRules';
}
else {
return "Prototype warning: no style rules changer for this browser"
}
for (var i=0;i<document.styleSheets.length;i++){
for (var j=0;j<document.styleSheets[i][myrules].length;j++) {
if (document.styleSheets[i][myrules][j].selectorText == myclass) {
document.styleSheets[i][myrules][j].style[myatt] = myval;
}
}
}
return "";
}
(注意,我是横幅风格缩进的不悔改的倡导者; - )...... http://en.wikipedia.org/wiki/Indent_style#Banner_style