
//通过对象字面量创建一个对象 var p1 = { elemen: document.getElementById("div2"), speed: 1, delay: 10, //一秒钟动一下 flagX: true, flagY: true, startX: 100, startY: 200, move: function () { var width = document.documentElement.clientWidth - this.elemen.offsetLeft; var height = document.documentElement.clientHeight - this.elemen.offsetTop; this.elemen.style.left = this.startX + document.documentElement.scrollLeft + 'px'; this.elemen.style.top = this.startY + document.documentElement.scrollTop + 'px'; this.startX = this.startX + this.speed * (this.flagX ? 1 : -1); if (this.startX <= 0) { this.flagX = true; this.startX = 0; } else if (this.startX >= width) { this.flagX = false; this.startX = this.width; } this.startY = this.startY + this.speed * (this.flagY ? 1 : -1); if (this.startY <= 0) { this.flagY = true; this.startY = 0; } else if (this.startY >= height) { this.flagY = false; this.startY = this.height; } }, run: function () { var begin = setInterval(this.move, this.delay); this.elemen.onmouseover = function () { clearInterval(begin); }; this.elemen.onmouseout = function () { begin = setInterval(this.move, this.delay); }; } }; p1.run();
run: function () {
// var begin = setInterval(this.move, this.delay); //这样给计时器赋值执行函数句柄,move函数体内this对象为window,不是p1,下面的mouseout同理
var me = this;////
var begin = setInterval(function () { me.move() }, this.delay);
this.elemen.onmouseover = function () {
clearInterval(begin);
};
this.elemen.onmouseout = function () {
var begin = setInterval(function () { me.move() }, me.delay);///注意此时this为elemen这个dom对象,不是p1
};
}