JavaScript - 循环函数

标签 javascript jquery setinterval

我有这段代码,它使用打字机动画替换搜索栏中的 placeholder 文本: https://codepen.io/anon/pen/vQmRjM

////////////////////////////
// Twitter: @mikedevelops
////////////////////////////

// your custome placeholder goes here!
var typetext = ["Text 1", "Text 2", "Text 3"];  
var typetext = typetext[Math.floor(Math.random() * typetext.length)];   
var searchBar = $('#search');
    // placeholder loop counter
var phCount = 0;

// function to return random number between
// with min/max range
function randDelay(min, max) {
    return Math.floor(Math.random() * (max-min+1)+min);
}

// function to print placeholder text in a 
// 'typing' effect
function printLetter(string, el) {
    // split string into character separated array
    var arr = string.split(''),
        input = el,
        // store full placeholder
        origString = string,
        // get current placeholder value
        curPlace = $(input).attr("placeholder"),
        // append next letter to current placeholder
        placeholder = curPlace + arr[phCount];

    setTimeout(function(){
        // print placeholder text
        $(input).attr("placeholder", placeholder);
        // increase loop count
        phCount++;
        // run loop until placeholder is fully printed
        if (phCount < arr.length) {
            printLetter(origString, input);
        }
    // use random speed to simulate
    // 'human' typing
    }, randDelay(50, 90));
}  

// function to init animation
function placeholder() {    
    $(searchBar).attr("placeholder", "");
    printLetter(typetext, searchBar);
}

window.setInterval(function(){
    placeholder();
    }, 3000);

我添加了一个 setInterval 以每隔几秒循环一次不同的 placeholder 文本,但是在第一次迭代后它才开始显示 undefined

我哪里出错了?

最佳答案

问题是您正试图从实际上并不存在的索引访问数组项。您必须在每次调用 setInterval() 时重置变量 phCount:

window.setInterval(function(){
  phCount = 0; // reset here
  placeholder();
}, 3000);

代码示例:

////////////////////////////
// Twitter: @mikedevelops
////////////////////////////

// your custome placeholder goes here!
var typetext = ["Text 1", "Text 2", "Text 3"];	
var typetext = typetext[Math.floor(Math.random() * typetext.length)];	
var searchBar = $('#search');
	// placeholder loop counter
var phCount = 0;

// function to return random number between
// with min/max range
function randDelay(min, max) {
  return Math.floor(Math.random() * (max-min+1)+min);
}

// function to print placeholder text in a 
// 'typing' effect
function printLetter(string, el) {
  // split string into character seperated array

  var arr = string.split(''),
  input = el,
  // store full placeholder
  origString = string,
  // get current placeholder value
  curPlace = $(input).attr("placeholder"),
  // append next letter to current placeholder
  placeholder = curPlace + arr[phCount];
  //console.log(curPlace + '::' + arr[phCount] + '::' + phCount)

  setTimeout(function(){
  // print placeholder text
  $(input).attr("placeholder", placeholder);
  // increase loop count
  phCount++;

  // run loop until placeholder is fully printed
  if (phCount < arr.length) {
    printLetter(origString, input);
  }
  // use random speed to simulate
  // 'human' typing
  }, randDelay(50, 90));
}  

// function to init animation
function placeholder() {	
  $(searchBar).attr("placeholder", "");
  printLetter(typetext, searchBar);
}

window.setInterval(function(){
  phCount = 0;
  placeholder();
}, 3000);
@import url(https://fonts.googleapis.com/css?family=PT+Sans:400,700);

html {
  background: linear-gradient(90deg, #00c6ff 10%, #0072ff 90%);  
  font-family: 'PT Sans', Helvetica, Arial, sans-serif;
  padding-top: 50px;
}

h1 {
  text-shadow: 1px 1px 10px rgba(black, .5);
}

h1, h2 {
  text-align: center;
  color: white;
  font-size: 2.5em;
  line-height: 1.3em;
  font-weight: 300;
}

h2 {
  margin-top: 100px;
  font-size: 1.3em;
  font-style: italic;
  font-weight: 100;
}

.body {
  width: 100%;
  height: 250px;
  box-sizing: border-box;
}

input {
  box-sizing: border-box;
  font-size: 13px;
  vertical-align: top;
}

.wrapper {
  text-align: center;
  position: relative;
  height: 80px;
  font-size: 0;
  top: 50%;
  transform: translateY(-50%);
}

.search {
  padding: 0 30px;
  font-size: 18px;
  width: 60%;
  max-width: 400px;
  height: 80px;
  border: 1px solid darken(white, 30%);
  border-radius: 20px 0 0 20px;
}

.submit {
  cursor: pointer;
  border: none;
  background: url('http://thesuiteworld.com/wp-admin/maint/search-icon-white-png-540.png') no-repeat center center, #1E1E20;
  background-size: 35px 35px;
  border-radius: 0 20px 20px 0;
  padding: 15px 25px;
  display: inline-block;
  width: 150px;
  height: 80px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body">
  <h1>Placeholder text with<br/> typing effect</h1>
  <div class="wrapper">
    <input class="search" type="text" id="search" />
    <input class="submit" type="submit" value=" " />
  </div>
</div>
<h2>Click search to reset</h2>

关于JavaScript - 循环函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53318168/

相关文章:

javascript - jQuery 的 AJAX 计时问题

javascript - 如何在 Google Map API v3 中区分鼠标左键和右键单击 mousedown 事件

jQuery 选择器仅选择特定的 2 个类,不包括任何其他类?

javascript - 递归函数和 setTimeout 与 setInterval

Javascript/jQuery - 重复检查 5 次迭代并在满足条件时运行另一个函数

javascript - 设置间隔为ajax形式

.net - Visual Studio 2008 和覆盖现有文件扩展名的语言服务

javascript - 使用 EaselJS 加载 sprite 表

javascript - 为什么使用同步功能 node.js

javascript - 我的 javascript 正在工作,但是当我在它下面添加另一个 javascript 代码和另一个 jquery 插件时,它变得一团糟?