在CSS弹出窗口中显示输入文本值

时间:2018-02-04 04:28:01

标签: javascript html css button input

我正在尝试通过单击输入按钮在弹出窗口中显示input文本的值。例如,如果我输入“James”并按下按钮,“James”将显示在pop-up中。 (以下举例)

但是,下面的code不适用于我的网站(也不适用于JSFiddle)。 它确实适用于Stack Snippet,相当奇怪。如何修复code以便它可以在任何地方使用?

JSFiddle(不工作) - https://jsfiddle.net/23wom1f7/

Stack Snippet(工作) -

function preview() {
  var fname = document.getElementById("fname").value;
  document.getElementById("modalname").innerHTML = fname;
}

var modal = document.querySelector(".modal");
var trigger = document.querySelector("#preview");
var closeButton = document.querySelector("#close");

function toggleModal() {
  modal.classList.toggle("show-modal");
}

function windowOnClick(event) {
  if (event.target === modal) {
    toggleModal();
  }
}

trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);
.modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  visibility: hidden;
  transform: scaleX(1.1) scaleY(1.1);
  transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s;
}

.modal-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  padding: 1rem 1.5rem;
  width: 24rem;
  border-radius: 0.5rem;
}

#close {
  float: right;
  width: 1.5rem;
  line-height: 1.5rem;
  text-align: center;
  cursor: pointer;
  border-radius: 0.25rem;
  background-color: lightgray;
}

#close:hover {
  background-color: darkgray;
}

.show-modal {
  opacity: 1;
  visibility: visible;
  transform: scaleX(1.0) scaleY(1.0);
  transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
}
<input class="formData" id="fname" type="text" maxlength="20" name="fname" placeholder="First Name" autocomplete="off">

<input type="button" class="formAsk" id="preview" onclick="preview()" name="preview" value="PREVIEW">

<div class="modal">
  <div class="modal-content">
    <span id="close">&times;</span>
    <h3>Preview Your Message:</h3> 
    Name: <span id="modalname"></span>
  </div>
</div>

1 个答案:

答案 0 :(得分:2)

这有效:https://jsfiddle.net/zsetxdrg/

基本上只是改变了这个......

this.preview = function() {
  var fname = document.getElementById("fname").value;
  document.getElementById("modalname").innerHTML = fname;
}

看起来像是一个范围问题,检查你的控制台没有看到preview()函数。