简体   繁体   English

切换显示将隐藏的元素显示一秒钟

[英]Toggle display shows the hidden element for a second

I'm trying to show a hidden text on click of a button. 我试图在单击按钮时显示隐藏的文本。 But when I load the page, the text shows for a second and then disappears. 但是,当我加载页面时,文本会显示一秒钟,然后消失。 Why would that happen? 为什么会这样?

<div class="container">
  <p class="temp">This is temporary</p>
  <button id="showme">Show</button>
</div>

$(document).ready(function() {
  $(".temp").hide();
  $("#showme").on("click", function() {
    $(".temp").show();
  });
});

Try to understand how the webpage loads. 尝试了解网页的加载方式。 Your jquery is executed when the entire page is rendered with the associated CSS. 当整个页面使用关联的CSS呈现时,将执行您的jquery。 So the browser displays your text for a second till it executes jquery to hide that text. 因此,浏览器将显示您的文本一秒钟,直到执行jquery隐藏该文本为止。 So your browser needs to know that this text is hidden while parsing the html. 因此,您的浏览器需要知道在解析html时此文本是隐藏的。 You can do this by giving a CSS style to the text. 您可以通过为文本提供CSS样式来做到这一点。

CSS: CSS:

.temp {
  display: none;
}

HTML: HTML:

<div class="container">
  <p class="temp">This is temporary</p>
  <button id="showme">Show</button>
</div>

JS: JS:

$(document).ready(function() {
  $("#showme").on("click", function() {
    $(".temp").show();
  });
});

You should use inline style tag in <p> tag like this: 您应该在<p>标记中使用内联样式标记,如下所示:

<p class="temp" style="display: none;">This is temporary</p>

instead of hiding it from jQuery! 而不是将其隐藏在jQuery中!

 $(document).ready(function() { $("#showme").on("click", function() { $(".temp").show(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <p class="temp" style="display: none;">This is temporary</p> <button id="showme">Show</button> </div> 

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

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