var xin = true, yin = true;
var step = 1;
var delay = 40;
var $obj = document.getElementById("ad")
var adTime = null;
var runFlag = false;
function clearAdTime() {
if (adTime) {
clearInterval(adTime)
adTime = null
}
}
runFlag = true
clearAdTime()
adTime = window.setInterval("move()", delay);
$obj.onmousemove = function() {
runFlag = false
clearAdTime()
}
$obj.onmouseout=function () {
clearAdTime()
runFlag = true
adTime = window.setInterval("move()", delay)
};
function closeAd () {
clearAdTime()
$obj.style.display = 'none'
}
function move() {
if (!runFlag) return
var left = $obj.offsetLeft;
var top = $obj.offsetTop;
var L = T = 0; //左边界和顶部边界
var R = window.innerWidth - $obj.offsetWidth; // 右边界
var B = window.innerHeight - $obj.offsetHeight; //下边界
//难点:怎样判断广告的4个边框有没有超出可视化范围!
if (left < L) {
xin = true; // 水平向右移动
}
if (left > R) {
xin = false;
}
if (top < T) {
yin = true;
}
if (top > B) {
yin = false;
}
//根据有没有超出范围来确定广告的移动方向
left += step * (xin == true ? 1 : -1);
top += step * (yin == true ? 1 : -1);
// 给div 元素重新定位
$obj.style.top = top + 'px';
$obj.style.left = left + 'px';
}