【问题标题】:javascript else of togglejavascript else of toggle
【发布时间】:2015-03-03 00:19:33
【问题描述】:

好的,我正在处理项目,我正在处理 2 号,我有切换问题,我似乎无法让它工作。

document.getElementsByClassName("buttons")[1].onmousedown=
    function(){
        colorchange();
    };
}
function colorchange() {

    /*var background = function blue(){document.getElementsByClassName("buttons")[1].style.border;*/
    if (getElementsByClassName("buttons")[1].style.border == "5px #c90 solid") {
        document.getElementsByClassName("buttons")[1].style.border="5px blue solid";
    } else {
        if (getElementsByClassName("buttons")[1] == "5px blue solid") {
        document.getElementsByClassName("buttons")[1].style.background = "5px #c90 solid";
    }

}
}

【问题讨论】:

  • 好奇,你用的是哪个调试器?

标签: javascript toggle


【解决方案1】:

这是一种方法:

window.onload = init;
var stateTwo = false, colorsThree = ['#cc9900','#1e3a03','#611790'];

function init(){
    var btns = document.getElementsByClassName("buttons");
    btns[0].onmousedown = btns[0].onmouseup = funcOne;
    btns[1].onclick = funcTwo;
    btns[2].onclick = funcThree;
}

function funcOne(e){
    this.style.background = ( e.type == 'mouseup' )? '#336600' : '#bd270a';
}

function funcTwo(e){
    stateTwo = !stateTwo;
    this.style.borderColor = stateTwo ? '#0c1583' : '#cc9900';
}

function funcThree(){
    colorsThree.push( colorsThree.shift() );
    this.style.borderColor = colorsThree[0];
}

JS Fiddle Demo

【讨论】:

  • 不确定我是否得到这个。似乎在使用jquery?我不能用这个。
  • @molliminous 没有 jQuery,只有纯 JS。你可能认为的 jQuery (variable = condition ? valueA : valueB) 实际上是一个 shorthand version of an if statement
  • @molliminous Here is a version 带有完整的if 语句。
  • 我明白了,我看了看,它工作得非常好,但我不确定我理解它为什么工作。有一些使用的东西我不确定它们为什么起作用。但我会自己查。谢谢
【解决方案2】:

你做的那一行:

if (getElementsByClassName("buttons")[1] == "5px blue solid")

应该是:

if (getElementsByClassName("buttons")[1].style.border == "5px solid blue")

【讨论】:

  • 是的,代码行丢失了,我可能在玩代码时忘记重新添加它。但它仍然不会触发。
猜你喜欢
  • 2019-12-24
  • 2021-07-13
  • 1970-01-01
  • 2022-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多