JavaScript
来源博客:【Harryの心阁】
元素偏移量
offset
Top/Left,动态的获取位置,具有定位的父元素的距离,如果没有则以body为准offsetWidth/Height
可以获取元素的大小 包括padding,borderoffsetParent
返回带有定位的父亲,否则是body,parentNode
返回最近一级 的父亲
offset和style
- style只能得到行内样式表中的样式值,并且获取的属性值是有单位的
- 获取元素使用offset更合适,更改样式使用style
<script>
var box =document.querySelector('.box');
box.addEventListener('click',function(e){
var x = e.pageX - this.offsetLeft;
console.log(x);
})
</script>
client系列
clientWidth
返回自身的宽度不包含边框,包含padding
立即执行函数
- 立即执行函数(function() {})() 或者(function(){}()),
- (function() {})() 第二个小括号可以看作调用函数
- (function(){}()), 多个立即执行函数要加
;
- 创建一个独立作用域,避免了命名冲突
<style>
.box {
position: relative;
margin-top: 200px;
margin-left: 100px;
top: 0;
left: 0;
width: 400px;
height: 400px;
background-color: rgb(163, 155, 155);
border-radius: 10px;
cursor: move;
}
.box .imgs {
position: absolute;
top: 0;
left: 0;
width: 64%;
margin-left: 74px;
margin-top: 3px;
vertical-align: middle;
}
.mask {
display: none;
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
border-radius: .625rem;
background-color: rgb(80, 29, 45);
opacity: .5;
}
.big {
display: none;
position: relative;
width: 600px;
height: 600px;
top: 0;
left: 410px;
border-radius: .625rem;
overflow: hidden;
}
.big .imgc {
position: absolute;
top: 0;
left: 0;
width: 300px;
margin-left: 100px;
}
</style>
<body>
<div class="box">
<img class="imgs" src="https://cdn.jsdelivr.net/gh/Rr210/hexofixed@1.07.01/img/api/phone/2ae5b713777378e1.jpg"
alt="">
<div class="mask"></div>
<div class="big"><img class="imgc"
src="https://cdn.jsdelivr.net/gh/Rr210/hexofixed@1.07.01/img/api/phone/2ae5b713777378e1.jpg" alt="">
</div>
</div>
<script>
var box = document.querySelector('.box');
var img = box.querySelector('.imgs');
var mask = box.querySelector('.mask');
var big = box.querySelector('.big');
var imgc = big.querySelector('.imgc');
box.addEventListener('mouseover', function () {
mask.style.display = 'block';
big.style.display = 'block';
})
box.addEventListener('mouseout', function () {
mask.style.display = 'none';
big.style.display = 'none';
})
box.addEventListener('mousemove', function (e) {
x = e.pageX - box.offsetLeft;
y = e.pageY - box.offsetTop;
maxX = x - mask.offsetWidth / 2;
maxY = y - mask.offsetHeight / 2;
var maxx = box.offsetWidth - mask.offsetWidth;
if (maxX <= 0) {
maxX = 0;
} else if (maxY <= 0) {
maxY = 0;
} else if (maxX >= maxx) {
maxX = maxx;
} else if (maxY >= maxx) {
maxY = maxx;
}
mask.style.left = maxX + 'px';
mask.style.top = maxY + 'px';
var bigmaxx = big.offsetWidth - imgc.offsetWidth;
var bigmaxy = big.offsetHeight - imgc.offsetHeight;
imgbx = maxX * bigmaxx / maxx;
imgby = maxY * bigmaxy / maxx;
imgc.style.left = -imgbx + 'px';
imgc.style.top = -imgby + 'px';
})
</script>