繁体   English   中英

如何用 javascript 隐藏此按钮 onclick?

[英]How can I hide this button onclick with javascript?

这是我的“查看更多”按钮的 javascript 代码。 我怎样才能让它在点击时消失?

    function myFunction() {
  var x = document.getElementById("dsec");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "block";
     }
  }
</script>

你需要给你的按钮一个 Id 并做你正在为你的描述块做的同样的事情。

IE:

function myFunction() {
  var x = document.getElementById("dsec");
  var btn= document.getElementById("btn");
  if (x.style.display === "none") {
    x.style.display = "block";
    btn.style.display = "none";
  } else {
    x.style.display = "none";
    btn.style.display = "block";
     }
  }
</script>

...或类似的。 我不完全确定是什么触发了您的“myFunction”或您的引用……但概念就在那里。

将来,值得添加更多上下文和拼写检查您的代码以使其更容易提供帮助。

我还会注意到@Scott Marcus 建议使用实际的 styles 而不是内联内容是更好的整体技术。

您应该尽可能避免内联 styles,而是依赖 CSS 类,它们要简单得多:

 // Get the references you'll need just once, not every time the function runs let content = document.querySelector(".partial"); // Set up event handlers using the modern, standard approach document.getElementById("seeMore").addEventListener("click", function(){ this.classList.add("hidden"); // Just add the CSS class content.classList.remove("partial"); // Show the full text });
 /* This class can be added or removed to any element when it needs to be shown or hidden. */.hidden { display:none; }.partial { height:40px; overflow:hidden; }
 <div class="partial">What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div> <button type="button" id="seeMore">See More</button>

请检查您的按钮 ID 和您的选择器,以确保其正确无误,无论如何这是一个有效的代码。 如果需要以简单的方式隐藏按钮,只需将其显示值设置为无即可。 这就像更改显示的 css 值,但您只是在使用 javascript。我相信您可以使用的另一个选项是将其从 DOM 中删除。

 function myFunction() { var x = document.getElementById("button"); x.style.display = "none"; //just let the css value of button to none }
 <button onclick="myFunction()" id="button">Click Me</button>

 var x = document.getElementById('button'); x.onclick = function () { document.getElementById('button').remove(); this.remove(); };
 <button onclick="myFunction()" id="button">Click Me</button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM