我写了一点javascript。这是我的第一个,我还在学习。我想减少行数并提高效率。我相信面向对象编程将是我最好的选择。
该脚本将一个类分配给悬停时的按钮。获取具有该类的元素并执行各种 if 函数以确定是否应更改图像按钮的 src 属性。该脚本还同时更改了另一个图像 src 属性。
我想知道是否可以以某种方式将 if 语句的逻辑压缩为一两个,然后使用变量执行 src 属性更改。但是我不知道该怎么做...?
//assign navButtons to var buttons (creates array)
var buttons = document.getElementsByClassName("navButton");
//set buttonHover function
function buttonOn(){
if ( arrow == topArrow.mouseout ) {
newArrow = document.getElementById("topArrow");
newArrow.setAttribute("src", topArrow.mouseover);
menuText.setAttribute("src", topArrow.text);
}
if ( arrow == rightArrow.mouseout ) {
newArrow = document.getElementById("rightArrow");
newArrow.setAttribute("src", rightArrow.mouseover);
menuText.setAttribute("src", rightArrow.text);
}
if ( arrow == bottomArrow.mouseout ) {
newArrow = document.getElementById("bottomArrow");
newArrow.setAttribute("src", bottomArrow.mouseover);
menuText.setAttribute("src", bottomArrow.text);
}
if ( arrow == leftArrow.mouseout ) {
newArrow = document.getElementById("leftArrow");
newArrow.setAttribute("src", leftArrow.mouseover);
menuText.setAttribute("src", leftArrow.text);
}
}
//set buttonHover function
function buttonOff(){
if ( arrow != topArrow.mouseout ) {
resetArrow = document.getElementById("topArrow");
resetArrow.setAttribute("src", topArrow.mouseout);
menuText.setAttribute("src", start.text);
}
if ( arrow != rightArrow.mouseout ) {
resetArrow = document.getElementById("rightArrow");
resetArrow.setAttribute("src", rightArrow.mouseout);
menuText.setAttribute("src", start.text);
}
if ( arrow != bottomArrow.mouseout ) {
resetArrow = document.getElementById("bottomArrow");
resetArrow.setAttribute("src", bottomArrow.mouseout);
menuText.setAttribute("src", start.text);
}
if ( arrow != leftArrow.mouseout ) {
resetArrow = document.getElementById("leftArrow");
resetArrow.setAttribute("src", leftArrow.mouseout);
menuText.setAttribute("src", start.text);
}
}
//for each instance of buttons, assign class "active" onmouseover
for(var i = 0; i < buttons.length; ++i){
buttons[i].onmouseover = function() {
this.className = "active";
arrow = document.getElementsByClassName("active");
//get attribute
arrow = arrow[0].getAttribute("src");
console.log(arrow);
buttonOn();
};
}
//for each instance of buttons, remove class "active" onmouseout
for(var i = 0; i < buttons.length; ++i){
buttons[i].onmouseout = function () {
arrow = document.getElementsByClassName("active");
//get attribute
arrow = arrow[0].getAttribute("src");
buttonOff();
this.className = "";
};
}
任何帮助都是王牌!