简体   繁体   中英

I am having trouble making a javascript typewriter effect

Its supposed to type one letter at a time when you open the page, however, it is not showing up at all. I'm a newbie at this javascript stuff.

HTML

<div class="wrap">
  <div class="test type" data-text="Hi, my name is John Doe"></div>
</div>

CSS

body {
  font: 16px/20px sans-serif;
}


.wrap {
  width: 500px;
  margin: 30px auto;
  text-align: center;
}

.test {
  margin-top: 10px;
  text-align: left;
}

JS

function typeWriter(text, n) {
  if (n < (text.length)) {
    $('.test').html(text.substring(0, n+1));
    n++;
    setTimeout(function() {
      typeWriter(text, n)
    }, 100);
  }
}

$('.type').click(function(e) {
  e.stopPropagation();

  var text = $('.test').data('text');

  typeWriter(text, 0);
});

 $(function(){ function typeWriter(text, n) { if (n < (text.length)) { $('.test').html(text.substring(0, n+1)); n++; setTimeout(function() { typeWriter(text, n) }, 100); } } $('.type').click(function(e) { e.stopPropagation(); var text = $('.test').data('text'); typeWriter(text, 0); }); }); 
 body { font: 16px/20px sans-serif; } .wrap { width: 500px; margin: 30px auto; text-align: center; } .test { margin-top: 10px; text-align: left; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="wrap"> <div class="test type" data-text="Hi, my name is John Doe">Click me</div> </div> 

You needed to add something to click. (I added the text 'click me' in the div).

Use this, I made it worked in less code. Another thing i did is used some random time to give real world effect..

 $(function(){ var txt = $(".type").data("text").split(""); txt.forEach(function(chr, i){ var rand = Math.floor(Math.random() * 100) + 1; setTimeout(function(){ $(".type").append( chr ); },300*(i+1) + rand) }) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="test type" data-text="Hi, my name is John Doe"></div> 

You may miss the CDN.

 <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> </head> 
Your codes are good.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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