单击按钮使文本显示/消失

时间:2019-03-31 15:29:36

标签: javascript html css html5 dom-events

我正在尝试使按钮使用'none'替代隐藏文本,而使用'block'替代显示文本。我尝试了下面的方法,但是没有用

def print_words(filename):
  my_file = (open(filename, 'r').readlines())
  word_dict = {}
  for line in my_file:
    line.lower()
    words_in_line = line.replace("\n","").split(" ")
    for word in words_in_line:
        if word in word_dict:
            word_dict[word] =word_dict[word]+ 1
        else:
            word_dict[word] = 1

我想将事件监听器转换为Javascript并从那里运行。

3 个答案:

答案 0 :(得分:2)

css:

.demo {
   display: none;
}

html:

<p id='demo' class='demo'>Hello Javascript</p>
<button type='button'> click me </button>

js:

var tag = document.getElementById('demo');
var button = document.querySelector('button');
button.addEventListener('click', function(){
tag.classList.toggle('demo');
});

正在运行的代码段:

var tag = document.getElementById('demo');
var button = document.querySelector('button');
button.addEventListener('click', function(){
tag.classList.toggle('demo');
});
.demo {
   display: none;
}
<p id='demo' class='demo'>Hello Javascript</p>
<button type='button'> click me </button>

答案 1 :(得分:1)

有帮助吗?

var showHide = document.getElementById("showHide");
var demo = document.getElementById("demo");
showHide.onclick = function() {
  if (demo.style.display == "block") {
    demo.style.display = "none";
  } else {
    demo.style.display = "block";
  }
}
<p id='demo' style='display: none'>Hello Javascript</p>
<button id="showHide">Click Me</button>

答案 2 :(得分:1)

尝试一下,希望对您有所帮助。谢谢

function toggleText() {
  var text = document.getElementById("demo");
  if (text.style.display === "none") {
    text.style.display = "block";
  } else {
    text.style.display = "none";
  }
}
<p id='demo' style='display: none'>Hello Javascript</p>     
<button type='button' onclick="toggleText()">Click me</button>