Hide and unhide a text after 6 seconds in a infini

2019-02-28 08:52发布

问题:

Hi i have created this script to hide a text after 6 seconds, But I want that the text must reappear and disappear again back to the infinite every 6 seconds how I can create this kind of HTML script?

<h1 style="text-align: left;" id="xhide">Hello World</h1>

<script type="text/javascript">
function hide(id) {
    d= document.getElementById(id)
    d.setAttribute('style','display:none;')
}
setTimeout(function () {
    hide('xhide')
}, 6000);
</script>

回答1:

You can try updated code as per your need:

<h1 style="text-align: left;" id="xhide">Hello World</h1>

<script type="text/javascript">
var flag=true;
function hide(id) {
    d= document.getElementById(id);
    d.setAttribute('style','display:none;');
}

function show(id) {
    d= document.getElementById(id)
    d.setAttribute('style','display:block;')
}
  
setInterval(function() {
    if(flag) {
        show('xhide');
        flag=false;
    } else {
       hide('xhide');
       flag=true;
    }
}, 6000);
</script>



回答2:

try this blink element

<script type="text/javascript">
  function blink() {
    var blinks = document.getElementsByTagName('blink');
    for (var i = blinks.length - 1; i >= 0; i--) {
      var s = blinks[i];
      s.style.visibility = (s.style.visibility === 'visible') ? 'hidden' : 'visible';
    }
    window.setTimeout(blink, 6000);
  }
  if (document.addEventListener) document.addEventListener("DOMContentLoaded", blink, false);
  else if (window.addEventListener) window.addEventListener("load", blink, false);
  else if (window.attachEvent) window.attachEvent("onload", blink);
  else window.onload = blink;
</script>
<blink>Text to blink here</blink>


回答3:

The following code will hide the text and re-display it with 6 second intervals in between.

var textshown = false;

$(document).ready(function() {  
  setInterval(function(){
    if(textshown == false) {
       $('#xhide').show();
       textshown = true;
    } else {
       $('#xhide').hide();
       textshown = false;
    }
  }, 6000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 style=" text-align: left; " id="xhide">Hello World</h1>



回答4:

You can do this by using toggle function on classList

function hide(elementId) {
  document.getElementById(elementId).classList.toggle('hidden');
}

setInterval(hide, 6000, 'xhide');
.hidden {
  display: none;
}
<h1 id="xhide">Hello World</h1>