首先,我必须说我处于非常基本的编程水平。这些问题的答案对某些人来说可能非常明显,但我想不出将所有这些放在一起的方法。提前谢谢。
我有这个 HTML 代码:
<div id="vectores" class="categoria" onclick="this.style.color='#000'; this.style.textDecoration='underline'; mostraVectores('vectores0','vectores')" onmouseover="this.style.color='#000'; this.style.textDecoration='underline'" onmouseout="this.style.color='#999'; this.style.textDecoration='none'">Tema 1. Mecánica vectorial</div>
<div id="vectores0" class="subcategoria"></div>
我在这里使用"onclick"来对样式进行"永久"的更改,因为我希望它是一个"菜单选项",我希望它触发功能,但也改变它的外观,以便可以轻松判断它是否已被选中。我使用"onmouseover"让用户一直知道指针"即将选择"的内容(菜单有更多选项)。
问题似乎是它们不会一起工作。我想这只是因为一旦通过"onmouseover"设置了新样式,如果第二个事件(onclick)要求,编译器就不会再次为div 设置相同的样式。
以下是该类的 css 代码:
.categoria{
color:#999;
font-weight:bold;
padding:2px;
padding-left:10px;
cursor:pointer;
}
然后我想使用单独的 javascript 页面和这样的函数使样式的更改"永久":
function mostraVectores(cosa1,cosa2){
document.getElementById(cosa1).style.display="block";
document.getElementById('equilibrio').style.color="#999";
document.getElementById('estructuras').style.color="#999";
document.getElementById('centros').style.color="#999";
document.getElementById('momento').style.color="#999";
document.getElementById('inercia').style.color="#999";
document.getElementById('rozamiento').style.color="#999";
document.getElementById('equilibrio').style.textDecoration="none";
document.getElementById('estructuras').style.textDecoration="none";
document.getElementById('centros').style.textDecoration="none";
document.getElementById('momento').style.textDecoration="none";
document.getElementById('inercia').style.textDecoration="none";
document.getElementById('rozamiento').style.textDecoration="none";
document.getElementById(cosa2).style.color="#000";
document.getElementById(cosa2).style.textDecoration="underline";
}
在这里,如您所见,还有其他"菜单选项",我想将其变为灰色并且没有下划线(因为它们最初是根据 css),以防此函数在其他函数之后执行,这样当用户从一个主题切换到另一个主题时,不会以两个"类似选择"菜单选项结尾。问题是,通过以这种方式"重置"样式,divs 中的"onmouseover/onmouseout"停止工作。
我该如何解决这个问题?
的方法是使用 CSS :hover
并在单击时分配一个类。
.HTML
<div id="vectores" class="categoria" onclick="mostraVectores('vectores0','vectores')">Tema 1. Mecánica vectorial</div>
<div id="vectores0" class="subcategoria"></div>
.CSS
.categoria {
color: #999;
font-weight: bold;
padding: 2px;
padding-left: 10px;
cursor: pointer;
}
.categoria:hover { /* This is applied on mouseover and removed on mouseout */
color: #000;
text-decoration: underline;
}
.categoria.active { /* Not sure what you want when clicked */
color: #900;
text-decoration: underline;
}
.JS
function mostraVectores(cosa1,cosa2){
//add this to your function
this.className += " active";