<div class="wrap" id="wrap1" >
<div class="targetWrap">
<br />
<span id="target1" class="target" >target</span>
<div style="width:600px;height:600px;overflow:hidded;background-color:rgba(1,1,1,.1);" ></div>
</div>
<div id="el1" class="el" >el</div>
</div>
<form id="set">
<textarea class="options" id="options">{
"baseOn":{
"el": "left top",
"target": "left bottom"
}
}</textarea>
<button type="submit" >Set</button>
</form>
.wrap {
width:200px;
height:200px;
border:1px solid #ABCDEF;
border-width: 1px 2px 3px 4px;
position:relative;
overflow-y: auto;
}
.targetWrap {
padding:50px;position:relative;
}
.target {
opacity: .8;
width:100px;height:100px;background-color:skyblue;
border:1px solid pink;
border-width: 1px 2px 3px 4px;
}
.el {
opacity: .8;
width:30px;height:30px;
background-color:purple;
/* useCssTransform */
transition: transform .3s;
}
.options{font-size:12px;height:8em;width:20em;}
将 el
定位到 target
左上角
var position = require('face-position')
position({
el: document.getElementById('el1'),
target: document.getElementById('target1')
})
document.getElementById('set').addEventListener('submit', function (e) {
e.preventDefault()
var json = document.getElementById('options').value
var options = JSON.parse(json)
options.el = document.getElementById('el1')
options.target = document.getElementById('target1')
options.useCssTransform = true
options.onPosition = function onPosition (postion, el, target, offsetParent) {
console.log(postion)
console.log({
elWidth: el.$overallWidth,
elHeight: el.$overallHeight,
targetWidth: target.$overallWidth,
targetHeight: target.$overallHeight,
})
return {
x:0,
y:0
}
}
position(options)
})
var box = document.createElement('div')
box.style.width = '20px'
box.style.height = '20px'
box.style.backgroundColor = 'orange'
document.body.appendChild(box)
position({
el: box,
target: document.getElementById('wrap1')
})
export default function () {
return {
baseOn: {
// "left/center/right top/center/bottom"
el: 'left top',
// "left/center/right top/center/bottom"
target: 'left bottom'
},
onPosition: function (position, el, target, offsetParent) {
return {
x:0,
y:0
}
},
useCssTransform: true,
}
}
<div id="centerTarget" style="border:1px solid red;">
abc
<div id="centerEl" style="width:100px;height:100px;background-color:rgba(124,124,141, 0.2)" >
</div>
</div>
var position = require('face-position')
position({
el: document.getElementById('centerEl'),
target: document.getElementById('centerTarget'),
baseOn: {
el: 'center',
target: 'center'
}
})
face-position
并没有监听窗口改变或dom改变时改变位置,如果你有这样的需求,请自行监听
onresize
.遇到极端情况需要实时定位时一定要使用 requestAnimationFrame
window.addEventListener('resize', function () {
position({
el: document.getElementById('el1'),
target: document.getElementById('target1')
})
})
requestAnimationFrame(function callee () {
position({
el: document.getElementById('el1'),
target: document.getElementById('target1')
})
requestAnimationFrame(callee)
})