我是JavaScript的新手,我很感激一些帮助。在此先感谢大家!
这是一个jsfiddle:http://jsfiddle.net/KYjF9/3/
我正在尝试使代码更优雅,并且在http://www.jslint.com/处有效(浏览器为true,继承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 :(得分:0)
var that = this;
setTimeout(function () {
that.tick();
}, delta);
这是that
变量的唯一用法。摆脱它:
setTimeout(this.tick.bind(this), delta);