Home > Article > Web Front-end > How to encapsulate common js functions
In front-end development, we often encounter such a problem, that is, when the page scrolls to a certain point, there will be a need to return to the top, so writing such a method on each page will make The code is very redundant; so in order to solve this problem, I extracted the code and encapsulated it into a public function for easy use. The encapsulation is not very good. If you have different opinions, you can discuss with each other~
/** * 页面回顶部 * @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; } }); }
The above is the detailed content of How to encapsulate common js functions. For more information, please follow other related articles on the PHP Chinese website!