如何将php函数产给js,如何将js常用函数进行封装

在前端的开发中,我们会经常遇到这样的一个问题,就是当页面滚动到一定的时候;会有回到顶部的需求,那么在每一个页面上都写这么一个方法就会使代码很冗余;所以为了解决这个问题;我把代码抽了出来,封装成一个公用的函数,方便使用。封装的还不是很好,有不同见解,可以相互讨论讨论~

686bd608ee3fa00ade3d9f8271f58a24-0.gif/** * 页面回顶部

* @obj //对象{}传入 ; 其中回顶部的imgSrc路径必传 ; 其他参数说明看函数内部的默认defaults对象

*/

function _backToTop(obj){

var defaults = {

pageHeight: 2, //默认当向下滚动2页时,显示

aId: 'aToTop', //a标签的id

href: 'backTop', //跳转到指定body元素的顶部

aStyle: { //a标签样式

width: '40px',

height: '40px',

display: 'block',

position: 'fixed',

right: '20px',

bottom: '50px',

zIndex: 99999 //z-index:999的这种样式以 zIndex:999的方式传值

},

imgStyle: { //img标签样式

width: '100%',

height: '100%' }

}; for (var def in defaults) { if (typeof obj[def] === 'undefined') { obj[def] = defaults[def];

} else if (typeof obj[def] === 'object') { for (var deepDef in defaults[def]) { if (typeof obj[def][deepDef] === 'undefined') { obj[def][deepDef] = defaults[def][deepDef];

}

}

}

}

//把样式对象转化为样式字符串,有如:z-index:999;的样式按 zIndex:999;的 方式传值

obj.aStyle =

JSON.stringify(obj.aStyle).replace(/{|}|"/g,'').replace(/,/g,';').replace(/[A-Z]/g, function(ch) {return '-'+String.fromCharCode(ch.charCodeAt(0) | 32);});

obj.imgStyle = JSON.stringify(obj.imgStyle).replace(/{|}|"/g,'').replace(/,/g,';').replace(/[A-Z]/g, function(ch) {return '-'+String.fromCharCode(ch.charCodeAt(0) | 32);});

var winHeight = document.documentElement.clientHeight || document.body.clientHeight;

var scrollValue;

document.getElementsByTagName('body')[0].setAttribute('id',obj.href);

var box = document.createElement('a');

var img = document.createElement('img');

box.setAttribute('id',obj.aId);

box.setAttribute('href','#'+obj.href);

box.setAttribute('style',obj.aStyle);

img.setAttribute('style',obj.imgStyle);

img.setAttribute('src',obj.imgSrc);

box.appendChild(img);

window.addEventListener('scroll',function(e){

scrollValue = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop; if(scrollValue > (winHeight * obj.pageHeight)){

document.body.appendChild(box);

}else{

document.getElementById(obj.aId) ?

document.body.removeChild(document.getElementById(obj.aId)) : null;

}

});

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值