2014-03-27 23 views
1

我對JavaScript非常陌生,我很感謝您的幫助。預先感謝你們所有人!在標題中插入和刪除字符/字

這裏有一個的jsfiddle:http://jsfiddle.net/KYjF9/3/

我試圖使代碼更優雅,也適用於http://www.jslint.com/(瀏覽器真,繼承2)?

非常感謝您的幫助!

HTML:

<html> 
    <body> 
    <h1>Test<span class="caption"></span></h1> 
    </body> 
</html> 

CSS:

h1 span.caption { 
     color:rgb(224,224,224); /*#e0e0e0*/ 
} 

h1 span.wrap { 
     border-right: 2px solid #f0f0f0 
} 

的JavaScript:

var TxtRotate = function (el, toRotate, period) { 
    "use strict"; 
    this.toRotate = toRotate; 
    this.el = el; 
    this.loopNum = 0; 
    this.period = parseInt(period, 10) || 2000; 
    this.txt = ''; 
    this.tick(); 
    this.isDeleting = false; 
}; 

TxtRotate.prototype.tick = function() { 
    "use strict"; 
    var i = this.loopNum % this.toRotate.length; 
    var fullTxt = this.toRotate[i]; 

    if (this.isDeleting) { 
    this.txt = fullTxt.substring(0, this.txt.length - 1); 
    } else { 
    this.txt = fullTxt.substring(0, this.txt.length + 1); 
    } 

    this.el.innerHTML = '<span class="wrap">' + this.txt + '</span>'; 

    var delta = 300 - Math.random() * 100; 

    if (this.isDeleting) { delta /= 2; } 

    if (!this.isDeleting && this.txt === fullTxt) { 
    delta = this.period; 
    this.isDeleting = true; 
    } else if (this.isDeleting && this.txt === '') { 
    this.isDeleting = false; 
    this.loopNum++; 
    delta = 500; 
    } 

    setTimeout(this.tick.bind(this), delta); 
}; 

// captions and interval 
var data = { 
    'caption': { 
    'rotate': '["communications", "design", "graphic design", "typography", "photography", "postproduction"]', 
    'period': "3000" 
    } 
}; 

window.onload = function() { 
    "use strict"; 
    var elements = document.getElementsByClassName('caption'); 
    for (var i=0; i<elements.length; i++) { 
    var toRotate = data.caption.rotate; 
    var period = data.caption.period; 
    //var toRotate = elements[i].getAttribute('data-rotate'); 
    //var period = elements[i].getAttribute('data-period'); 
    if (toRotate) { 
     new TxtRotate(elements[i], JSON.parse(toRotate), period); 
    } 
    } 
}; 

$(function() { 
    var onClass = "on"; 
    var showClass = "show"; 

    $("input").bind("checkval",function() { 
    var label = $(this).prev("label"); 
    if(this.value !== "") { 
     label.addClass(showClass); 
    } else { 
     label.removeClass(showClass); 
    } 
    }).on("keyup",function() { 
    $(this).trigger("checkval"); 
    }).on("focus",function() { 
    $(this).prev("label").addClass(onClass); 
    }).on("blur",function() { 
     $(this).prev("label").removeClass(onClass); 
    }).trigger("checkval"); 
}); 
+0

您的jsfiddle不工作,你需要選擇一個jQuery庫,並從下拉列表中 – markpsmith

+0

對不起,我更新的鏈接選擇onDomready! – fooness

+1

我覺得這個問題屬於http://codereview.stackexchange.com/ –

回答

0
var that = this; 

setTimeout(function() { 
    that.tick(); 
}, delta); 

這裏的that變量的唯一用途。擺脫它:

setTimeout(this.tick.bind(this), delta); 
+0

非常感謝! – fooness