隐藏的按钮在显示时不是内联的

时间:2018-08-26 21:44:54

标签: javascript html css

我有一个html页面,上面有一个名为 new 的按钮。

function handle_new() {
  document.getElementById('coki').style.display = "block";
  document.getElementById('btn_new1').style.display = "block";
  document.getElementById('btn_new2').style.display = "block";
  document.getElementById('btn_new2').style.display = "none";
  document.getElementById('btn_new4').style.display = "block";
}
.inline {
  display: inline-block;
}
<p>
  <button class="button button3" id="btn_new" type="button" onclick="handle_new();">New</button>
</p>

<div class="inline" id="coki" style="display: none">
  <button class="inline" id="btn_new1" type="button" onclick="handle_new1();">New</button>
  <button class="inline" id="btn_new2" type="button" onclick="handle_new2();">New</button>
  <button class="inline" id="btn_new3" type="button" onclick="handle_new3();">New</button>
  <button class="inline" id="btn_new4" type="button" onclick="handle_new4();">New</button>
  <button class="inline" id="btn_new5" type="button" onclick="handle_new5();">New</button>
</div>

当有人按下此按钮时,会显示5个按钮(按coki div),但始终位于彼此下方,而不是在同一行中。问题是我在按钮和div标签中也都包含了内联,但是由于某些原因,当我不添加任何显示内容时,它们始终显示在彼此的下方,而不是彼此相邻。

Td标签和p标签而不是div也不起作用。解决办法是什么?谢谢

1 个答案:

答案 0 :(得分:2)

相反,创建一个display: none类。 将其分配给所需的元素。
在按钮上单击,只需删除该none className。
元素应返回到其初始状态(内联块)

function handle_new() {
  document.getElementById('coki').classList.remove("none");
}
.inline {
  display: inline-block;
}

.none {
  display: none;
}
<p>
  <button class="button button3" id="btn_new" type="button" onclick="handle_new();">New</button>
</p>

<div class="inline none" id="coki">
  <button class="inline" id="btn_new1" type="button" onclick="handle_new1();">New</button>
  <button class="inline" id="btn_new2" type="button" onclick="handle_new2();">New</button>
  <button class="inline" id="btn_new3" type="button" onclick="handle_new3();">New</button>
  <button class="inline" id="btn_new4" type="button" onclick="handle_new4();">New</button>
  <button class="inline" id="btn_new5" type="button" onclick="handle_new5();">New</button>
</div>

P.S:看到您的handle_newNNN(),恐怕您正在重复很多JS代码...但这是第二天的话题。


嗯,如果我猜对了你在做什么-那就是
有一个 Create New 按钮,用于创建元素。依此类推。这是我的处理方式:

var btnNew = document.getElementById("btn_new");
var elCoki = document.getElementById("coki");
var itemsTot = 0; // Currently 0 items created. We'll increment on creation
var itemsMax = 5; // max number of new items

function newItem() {
  itemsTot += 1;
  var item = document.createElement('div');
  item.classList.add("item")
  item.innerHTML = "THIS IS ITEM n."+ itemsTot +" !";
  elCoki.appendChild(item);
  // Disable button
  if(itemsTot >= itemsMax) {
    btnNew.disabled = true;
    btnNew.classList.add("none");
  }
}

btnNew.addEventListener("click", newItem);
.item {
  background: orange;
  padding: 4px; margin: 2px 0;
}
.none {
  display: none;
}
<div id="coki"></div>
<button class="button button3" id="btn_new" type="button">+ New Item</button>

相关问题