簡體   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