特效介绍
纯js实现的悬浮窗广告效果代码,遇到窗口边缘会自动弹回来。我爱模板网亲测可用。效果可以点击文章末尾的预览按钮,查看。
使用方法
第一种效果js代码:
var x = 50,y = 60 var xin = true, yin = true var step = 1 var delay = 10 var obj=document.getElementById("fuchuang") function float() { var L=T=0 var R= document.body.clientWidth-obj.offsetWidth var B = document.body.clientHeight-obj.offsetHeight obj.style.left = x + document.body.scrollLeft + 'px' obj.style.top = y + document.body.scrollTop + 'px' x = x + step*(xin?1:-1) if (x < L) { xin = true; x = L } if (x > R){ xin = false; x = R } y = y + step*(yin?1:-1) if (y < T) { yin = true; y = T } if (y > B) { yin = false; y = B } } var itl= setInterval(()=>{ float() }, delay) obj.onmouseover=function(){clearInterval(itl)} obj.onmouseout=function(){itl=setInterval(()=>{ float() }, delay)}
第二种效果js代码:
var img1 = document.querySelector('#fuchuang') var xPos = 300; var yPos = 200; var step = 1; var delay = 5; var height = 0; var Hoffset = 0; var Woffset = 0; var yon = 0; var xon = 0; var pause = true; var interval; img1.style.top = yPos + 'px'; function changePos(){ width = document.body.clientWidth; height = document.body.clientHeight; Hoffset = img1.offsetHeight; Woffset = img1.offsetWidth; img1.style.left = xPos + document.body.scrollLeft + 'px'; img1.style.top = yPos + document.body.scrollTop + 'px'; if (yon) { yPos = yPos + step; } else { yPos = yPos - step; } if (yPos < 0) { yon = 1; yPos = 0; } if (yPos >= (height - Hoffset)) { yon = 0; yPos = (height - Hoffset); } if (xon) { xPos = xPos + step; } else { xPos = xPos - step; } if (xPos < 0) { xon = 1; xPos = 0; } if (xPos >= (width - Woffset)) { xon = 0; xPos = (width - Woffset); } } function start() { img1.visibility = 'visible'; interval = setInterval(() => { changePos() }, delay); } function pause_resume() { if (pause) { clearInterval(interval); pause = false; } else { interval = setInterval(() => { changePos() },delay); pause = true; } } start();