【问题标题】:A link reveals an image and hides itself链接显示图像并隐藏自身
【发布时间】:2019-01-03 21:24:20
【问题描述】:

我对编码完全陌生,我想知道如何编写一个链接,该链接在显示隐藏图像的同时使用 HTML 隐藏自身。根据我收集到的信息,这应该可行:

<a href="javascript:onoff()" id="QRText" onclick="myFunction();"=>Click to reveal QR code</a>
<img hidden alt="QR Code" id="revealonclick" src="https://erallie.weebly.com/uploads/1/1/8/6/118611729/published/qr-code-erallie-s-app.png?1532624405">


<script>
function myFunction() {
    alert("The app is in the form of a webpage. Don't forget to add the webpage to your homescreen!");
</script>


        <script type="text/javascript">
            function onoff() {
                if (document.getElementById)
                 document.getElementById("QRText").style.visibility = "hidden";
                 if (document.getElementById)
                 document.getElementById("revealonclick").style.visibility = "visible";
            }
        </script>

隐藏链接有效,通知有效,但由于某种原因,当我尝试将多个参数添加到一个函数中时,它似乎不起作用。我做错了什么?

【问题讨论】:

  • 您的函数myFunction 中存在语法错误。这是你的完整代码吗?

标签: javascript html visibility


【解决方案1】:

您的代码中有几个语法错误。以下应该可以工作。

function myFunction() {
  alert("The app is in the form of a webpage. Don't forget to add the webpage to your homescreen!");
}

function onoff() {
  var elem1 = document.getElementById("QRText");
  var imgElem = document.getElementById("revealonclick");
  if (elem1 && imgElem) {
    elem1.style.visibility = "hidden";
    imgElem.style.visibility = "visible";
  }
}
<a href="javascript:onoff()" id="QRText" onclick="myFunction()">Click to reveal QR code</a>
<img style="visibility: hidden;" alt="QR Code" id="revealonclick" src="https://erallie.weebly.com/uploads/1/1/8/6/118611729/published/qr-code-erallie-s-app.png?1532624405">

【讨论】:

    【解决方案2】:

    首先,您的 myFunction 定义中缺少右括号。不过,在此处粘贴您的代码时,这可能只是一个错误。

    您正在使用 style.visibility 试图使您的图像可见,但这并不是首先使其不可见的原因。如果要使用 Visibility 属性使其可见,则需要使用相同的属性使其不可见。

    function myFunction() {
      alert("The app is in the form of a webpage. Don't forget to add the webpage to your homescreen!");
    }
    
    function onoff() {
      if (document.getElementById) {
        document.getElementById("QRText").style.visibility = "hidden";
        document.getElementById("revealonclick").style.visibility = "visible";
      }
    }
    <a href="javascript:onoff()" id="QRText" onclick="myFunction();"=>Click to reveal QR code</a>
    <img style="visibility: hidden;" alt="QR Code" id="revealonclick" src="https://erallie.weebly.com/uploads/1/1/8/6/118611729/published/qr-code-erallie-s-app.png?1532624405">

    这可行,但是您会注意到,如果您的链接仍然可见,图片会显示在该位置。这是因为使用 visibility: hidden 会使项目不可见,但它仍会占用 DOM 中的空间。要让它“更彻底”消失,您可以使用“display: none;”和“显示:内联;”或“显示:块;”而是。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-01
      • 2023-03-30
      • 2013-09-21
      • 1970-01-01
      相关资源
      最近更新 更多