今天要帮人实现一个可以在窗口上飘来飘去的广告,虽然对这类漂浮移动的广告很不感冒,但是写还是得写的。
原理知道,但是自己写,总是麻烦,就去网上找了个demo,然后再基于那个demo做了点修改。
话不多说,上代码:
<meta charset="UTF-8">
<title>Document</title>
<style>
body{
/*height: 600px;*/
}
.ad{
position: absolute;
top: 0px;
left: 0px;
width: 100px;
height: 90px;
z-index: 1000;
}
.ad img{
display: block;
width: 100px;
height: 90px;
margin: 0;
padding: 0;
border: medium none;
}
</style>
<div id="flw" class="ad"><iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe><a href="http://www.baidu.com/"><img src="https://www.shuizhongyueming.com:8080/wp-content/uploads/2015/01/screen-icon.png" alt=""></a></div>
<script>
/* requestAnimationFrame.js
* by zhangxinxu 2013-09-30
*/
(function() {
var lastTime = 0;
var vendors = ['webkit', 'moz', 'ms'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] ||
window[vendors[x] + 'CancelAnimationFrame'] ||
window[vendors[x] + 'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16.7 - (currTime - lastTime));
var id = window.setTimeout(function() {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
}());
var x = 0,
y = 0,
step = 2,
xin = true,
yin = true,
doc = document,
domBody = doc.body,
domDoc = document.documentElement,
domFlw = doc.getElementById('flw'),
domFlwWidth = domFlw.offsetWidth,
domFlwHeight = domFlw.offsetHeight;
var L=0;
var T=0;//L左边界,T上边界
(function flwAd(){
requestAnimationFrame(flwAd);
// 需要考虑窗口变化的情况,所以没缓存,也可以缓存,然后注册window 的resize事件
var R=domDoc.clientWidth - domFlwWidth;
var B= domDoc.clientHeight - domFlwHeight;
domFlw.style.left=x+domBody.scrollLeft+'px'; //层显示的左边距 随着滚动条而滚动
domFlw.style.top=y+domBody.scrollTop+'px'; //层显示的上边距
// console.log(x, L, R);
// console.log(y, T, B);
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;
}
})();
</script>
效果看这里:
主要的修改有如下几点:
- requestAnimationFrame – 使得在高级浏览器下的性能呢更好
- document.documentElement.clientHeight/clientWidth – W3C标准的获取窗口尺寸的方法
- 数据缓存 把部分固定不变的变量移动到动画主函数之外,避免多余的计算消耗和DOM查找
原创内容,欢迎转载 😊