forked from KenyeeC/eleFixed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheleFixed.js
73 lines (64 loc) · 2.44 KB
/
eleFixed.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
(function(){
var eleFixed = {
targets: [],
push: null,
distory: null,
handler: null,
delete: null
}
// push exefixed instance
eleFixed.push = function (option) {
if(typeof option !== 'object') return console.error('eleFixed: push param must be a Object')
if(!option.target && !isElement(option.target)) return console.error('eleFixed: target must be a HTMLElement')
if(!option.offsetTop && typeof option.offsetTop !== 'number') return console.error('eleFixed: param\'s offsetTop must be a Number')
window.eleFixed.targets.push(option)
}
// eleFixed handler
eleFixed.handler = function(){
var offsetTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
for(var i in eleFixed.targets){
if(offsetTop > eleFixed.targets[i].offsetTop){
eleFixed.targets[i].target.style.transform = 'translateY('+ (offsetTop - eleFixed.targets[i].offsetTop) +'px)'
}else{
eleFixed.targets[i].target.style.transform = 'translateY(0px)'
}
}
}
// delete one eleFixed instance
eleFixed.delete = function (target) {
if(target && isElement(target)){
var targets = window.eleFixed.targets
for(var i in targets){
if(target.isEqualNode(targets[i].target)){
target.style.transform = 'translateY(0px)'
targets.splice(i, 1)
break
}
}
}
}
// distory eleFixed in window
eleFixed.distory = function () {
window.removeEventListener('scroll', eleFixed.handler)
for(var i in window.eleFixed.targets){
window.eleFixed.targets[i].target.style.transform = 'translateY(0px)'
}
window.eleFixed = null
}
// helper
function isElement(value) {
return (
typeof HTMLElement === 'object' ? value instanceof HTMLElement :
value && typeof value === "object" && value !== null && value.nodeType === 1 && typeof value.nodeName==="string"
)
}
// umd expose
if (typeof exports == "object") {
module.exports = eleFixed
} else if (typeof define == "function" && define.amd) {
define(function(){ return eleFixed })
} else {
this.eleFixed = eleFixed
}
window.addEventListener('scroll', eleFixed.handler)
})()