vanilla js onclick如果声明问题

时间:2016-01-21 13:58:18

标签: javascript if-statement

我试图在点击其他元素时影响元素高度的更改。我使用if else语句来来回切换更改。

var bnr = document.getElementById("bnr");
var btn = document.getElementById('btn');

if (bnr.style.height = "250px") { 
  btn.onclick = function() {
    bnr.style.height = "600px";
  };
}   
else if (bnr.style.height = "600px") { 
  btn.onclick = function() {;
    bnr.style.height = "250px";
  };
};

第一个语句有效,将元素高度更改为600px但第二个语句不起作用,如果再次单击,则元素保持在600px。

有人能够看到我在哪里出错吗?

JS Fiddle example

3 个答案:

答案 0 :(得分:0)

您的代码在页面加载(我假设)上运行,并且当该高度为250 px时,会创建一个单击事件以将高度设置为600 px。每次单击该按钮时,都会运行相同的事件,因为问题中的代码将不再运行。我想你想要:

{
    "filterSummary": [{
        "field": "vanity_width_88",
        "value": {
            "rangeLow": "15",
            "rangeHigh": "24"
        },
        "label": "Vanity Width: 16\" to 24\"",
        "filterLabel": "Vanity Width",
        "filterValue": "16\" to 24\""
    }, {
        "field": "vanity_width_88",
        "value": {
            "rangeLow": "35",
            "rangeHigh": "42"
        },
        "label": "Vanity Width: 35 to 42",
        "filterLabel": "Vanity Width",
        "filterValue": "35 to 42"
    }]
}

答案 1 :(得分:0)

你这样做是这样的:

var bnr = document.getElementById("bnr");
var btn = document.getElementById('btn');

btn.onclick = function() {
  if (bnr.style.height == "250px" || !bnr.style.height)
  { 
      bnr.style.height = "600px";
  }     
  else if(bnr.style.height == "600px")
  { 
      bnr.style.height = "250px";
  };      
};

https://jsfiddle.net/crfdhtes/1/

答案 2 :(得分:0)

最好使用类操作来改变元素的样式。所以你可以添加“扩展”类:

var btn = document.getElementById('btn');

btn.onclick = function() {
  var bnr = document.getElementById('bnr');
  bnr.classList.toggle('expanded');
};

并在点击时切换:

resValue "string", "host_name", InetAddress.localHost.canonicalHostName