let child = document.querySelector('.child');
let father = document.querySelector('.father');
child.onclick = function (e) {
console.log(e.target);
}
/*
this.offsetLeft获取的是元素距离页面边界的距离,不是父元素的
e.pageX获取的是点击事件的在页面中的横坐标,
e.offsetX获取的是点击事件在元素内部的横坐标,
要想获得子元素在父元素中的相对距离,需要child.offsetLeft - father.offsetLeft
this.offsetWidth获取的是元素的可见宽度,
window.pageYOffset==
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 案例
# 固定的侧边栏
if (window.pageYOffset >=element.offsetTop) {
sliderbar.style.position = 'fixed';
sliderbar.style.top = sliderbarTop + 'px';
} else {
sliderbar.style.position = 'absolute';
sliderbar.style.top = '300px';
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# 回到顶部
var goBack = document.querySelector('.goBack');
var nav = document.querySelector('nav');
window.addEventListener('scroll', function () {
if (window.pageYOffset >= nav.offsetTop) {
goBack.style.display = 'block';
} else {
goBack.style.display = 'none';
}
});
goBack.addEventListener('click', function () {
window.scroll(0, 0);
})
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 模拟拖拽框
box2.addEventListener('mousedown', function(e) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;鼠标在盒子中的位置
document.addEventListener('mousemove', move);
function move(e) {
box2.style.left = e.pageX - x + 'px';
box2.style.top = e.pageY - y + 'px';
}
document.addEventListener('mouseup', function() {
document.removeEventListener('mousemove', move);
})
})
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# tab栏切换
$(function () {
$(".tab_list li").click(function () {
$(this).addClass("current").siblings().removeClass("current");
$(".tab_con div").eq($(this).index()).css("display", "block").siblings().hide();
})
})
1
2
3
4
5
6
2
3
4
5
6