使用JavaScript的功能表单检查未出现

时间:2019-01-10 08:27:36

标签: javascript html css

无论何时单击按钮,我都在测试弹出窗口。我将它放在div标签中,并使用display隐藏:无。我试图使它在我单击按钮时出现,但是什么也没显示。

HTML:

表格:

<div class="form_main_bg">
</div>
<div class="form_box">
  <div class="form_header">Pop out</div>
  <div class="form_body"></div>
  <div class="form_footer">
    <button class="btn form-control color-white mwc-orange-background-color" onclick="closeform()">Close</button>
  </div>
</div>

按钮:

<input type="submit" class="btn form-control color-white mwc-orange-background-color" id="register" name="register" value="REGISTER" onclick="formcheck()">

Javascript:

function  closeform() {
  var main_bg = document.getElementByClass("form_main_bg");
  var f_box = document.getElementByClass("form_box");
  main_bg.style.display = "none";
  f_box.style.display = "none";
}

function formcheck() {

    var main_bg = document.getElementByClass("form_main_bg");
    var f_box = document.getElementByClass("form_box");
    main_bg.style.display = "block";
    f_box.style.display = "block";

    var winWidth = window.innerWidth;
    var winHeight = window.innerHeight;

    f_box.style.left = (winWidth/2) - 400/2 + "px";
    f_box.style.top = "150px";
}

更新:我尝试了“ getElementByClass”,仍然没有效果。

我也尝试过:querySelector('。form_main_bg');和getElementsByClassName(“ form_main_bg”);还是没事

1 个答案:

答案 0 :(得分:2)

您的代码中有两个问题。

首先,该函数不是document.getElementByClass,而是document.getElementsByClassName

第二,document.getElementsByClassName的结果将是一个包含所有具有指定类的元素的数组。因此,您必须在应用样式之前从结果中选择一个项目。 (main_bg[0].style.display

请参见下面的代码。

function closeform() {
  var main_bg = document.getElementsByClassName("form_main_bg");
  var f_box = document.getElementsByClassName("form_box");
  main_bg[0].style.display = "none";
  f_box[0].style.display = "none";
}

function formcheck() {

  var main_bg = document.getElementsByClassName("form_main_bg");
  var f_box = document.getElementsByClassName("form_box");
  main_bg[0].style.display = "block";
  f_box[0].style.display = "block";

  var winWidth = window.innerWidth;
  var winHeight = window.innerHeight;

  f_box[0].style.left = (winWidth / 2) - 400 / 2 + "px";
  f_box[0].style.top = "150px";
}
<div class="form_main_bg">
</div>
<div class="form_box">
  <div class="form_header">Pop out</div>
  <div class="form_body"></div>
  <div class="form_footer">
    <button class="btn form-control color-white mwc-orange-background-color" onclick="closeform()">Close</button>
  </div>
</div>

<input type="submit" class="btn form-control color-white mwc-orange-background-color" id="register" name="register" value="REGISTER" onclick="formcheck()">