【自我开发】开发一个返回顶部插件(谷歌插件编写方法)
第一步:编写manifest.json
{
“name”: “Back To Top”,
“description”: “返回顶部”,
“version”: “0.1”,
“content_scripts”: [ //在内容中加载js
{
“matches”: [“http:///“], //匹配页面,哪些页面需要显示
“js”: [“top.js”] //加载的js
}
],
“manifest_version”: 2,
“default_icon”: “icon_128.png”, //设置默认图片
“icons”: { “128”: “icon_128.png” } //图标
}
第二部:添加返回顶部的纯js
(function() {
var btnId = ‘__gotop’;
var isIE = !!window.ActiveXObject && /msie (\d)/i.test(navigator.userAgent) ? RegExp[‘$1’] : false;
function $() {
return document.getElementById(arguments[0]);
}
function getScrollTop() {
return (‘pageYOffset’ in window) ? window.pageYOffset
: document.compatMode === “BackCompat”
&& document.body.scrollTop
|| document.documentElement.scrollTop ;
}
function bindEvent(event, func) {
if (window.addEventListener) {
window.addEventListener(event, func, false);
} else if (window.attachEvent) {
window.attachEvent(‘on’ + event, func);
}
}
bindEvent(‘load’,
function() {
var css = ‘background-color:#999;width:50px;height:50px;position:fixed;right:100px;bottom:30px;border-radius:10px;cursor:pointer;display:none;’;
if (isIE && isIE < 7) {
css += ‘_position:absolute;_top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-30-this.offsetHeight-(parseInt(this.currentStyle.marginTop,10)||0)-(parseInt(this.currentStyle.marginBottom,10)||0)))’;
var style = document.createStyleSheet();
style.cssText = ‘*html{background-image:url(about:blank);background-attachment:fixed;}’;
}
var html = ‘
var el = document.createElement(‘DIV’);
el.id = btnId;
el.style.cssText = css;
el.innerHTML = html;
document.body.appendChild(el);
el.onclick = function() {
(function() {
var top = getScrollTop();
if (top > 0) {
window.scrollTo(0, top / 1.2)
setTimeout(arguments.callee, 10);
}
})();
};
el.onmouseover = function() {
$(btnId).firstChild.style.borderBottom = ‘14px solid #ddd’;
$(btnId).firstChild.firstChild.style.backgroundColor = ‘#ddd’;
};
el.onmouseout = function() {
$(btnId).firstChild.style.borderBottom = ‘14px solid #fff’;
$(btnId).firstChild.firstChild.style.backgroundColor = ‘#fff’;
};
}
);
bindEvent(‘scroll’,
function() {
var top = getScrollTop(), display = ‘none’;
if (top > 0) {
display = ‘block’;
}
$(btnId).style.display = display;
});
})();
第三步:打包上传