问题
I have navigation buttons that increase in width from 100px, to 150px when hovered over :
nav li:hover{
width:150px;
}
But using javascript I have made it so that which ever option has been selected, will continue to have a width of 150px. When each option is selected, it makes the other options go back to 100px as I intended :
function show1(){
document.getElementById("nav1").style.width="150px";
document.getElementById("nav2").style.width="100px";
document.getElementById("nav3").style.width="100px";
}
function show2(){
document.getElementById("nav2").style.width="150px";
document.getElementById("nav1").style.width="100px";
document.getElementById("nav3").style.width="100px";
}
function show3(){
document.getElementById("nav3").style.width="150px";
document.getElementById("nav1").style.width="100px";
document.getElementById("nav2").style.width="100px";
}
The problem is, once one of the navigation options has been selected, they no longer increase in width to 150px when hovered over, because the functions have set them to stay at 100px.
I am trying to work out how to make it so that each of the navigation buttons always increases in width when hovered over, while whichever one has been selected stays at the increased length. So i'm trying to find a way to reset the width value to how it is defined by my CSS after each function is executed.
Anyone know how to solve this? I'm fairly beginner level at javacript.
回答1:
I would do this by putting the "selected" style in a separate CSS class, and dynamically adding that class to the objects you want to have the fixed width, then dynamically removing it.
Fiddling with CSS classes in JS is not very difficult; see here for example.
回答2:
Make it an empty string and it takes over the one from your stylesheet again
document.getElementById("nav2").style.width = "";
回答3:
You should make use of classes and forget about modifying styles using javascript, you can see how inconvenient it is. Consider this example and how it simplifies everything:
CSS:
nav li:hover,
nav li.selected {
width: 150px;
background: coral;
}
and JS:
var selected = document.getElementsByClassName('selected');
function show(obj) {
if (selected.length) selected[0].className = '';
obj.className = "selected";
}
Here we go. Instead of three duplicated functions showX
you now have only one.
Demo: http://jsfiddle.net/zGfLP/
It can be further improved if you move get rid of the onclick handlers from HTML:
var nav = document.getElementById('nav'),
selected = nav.getElementsByClassName('selected');
nav.onclick = function(e) {
if (e.target.nodeName === 'LI') {
if (selected.length) selected[0].className = '';
e.target.className = "selected";
}
};
Demo: http://jsfiddle.net/zGfLP/1/
来源:https://stackoverflow.com/questions/22673097/how-to-reset-a-css-attribute-thats-been-changed-using-javascript