最终样式
所用知识点:
dom知识点:
可视宽,高 document.documentElement.clientWidth / document.documentElement.clientHeight
实际宽,高 document.documentElement.scrollWidth/document.documentElement.scrollHeight
滚动条距离上,左边的距离 document.documentElement.scrollTop/document.documentElement.scrollLeft
元素样式宽,高 width / height
元素内容宽,高 ele.clientWidth / ele.clientHeight padding+width / padding+height
实际宽,高 ele.offsetWidth / ele.offsetHeight padding+border+width /padding+border+height
相对父元素的距离 ele.offsetTop / ele.offsetLeft
DOM样式:
ele.style.property=value
property(属性)内的值不支持-,当出现-时,将其去掉,并采用驼峰命名法,例font-size为fontSize
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>29练习2_顶部悬浮</title>
<style>
* {
padding: 0;
margin: 0;
font-size: 18px;
}
body {
height: 3000px;
}
.top {
height: 600px;
display: flex;
align-items: stretch;
justify-content: center;
background: yellow;
}
.container {
display: flex;
}
.left {
background: green;
height: 300px;
width: calc(100% - 300px);
}
.right {
width: 300px;
height: 300px;
background: pink;
}
</style>
</head>
<body>
<div id="topContent" class="top">
我是上部内容
</div>
<div class="container">
<div class="left">
我是左侧内容
</div>
<div id="right" class="right">
我是右侧内容
</div>
</div>
</body>
<script>
var oTop = document.querySelector('.top');
var oRight = document.querySelector('.right');
//窗口的滚动条滚动时触发此事件
window.onscroll = function () {
//解决IE浏览器的兼容问题
var root = document.documentElement || document.body;
//root.scrollTop 为滚动条相对于文档上方的高度,oTop.offsetHeight为oTop该元素的实际高度
//若滚动条滚动高度大于等于oTop元素的实际高度是触发此事件
if (root.scrollTop >= oTop.offsetHeight) {
//对oRight事件进行绝对定位
oRight.style.position = 'fixed';
oRight.style.right = '0px';
oRight.style.top = '0px';
} else {
//对oRight事件回复原值
oRight.style.position = 'initial';
oRight.style.right = 'initial';
oRight.style.top = 'initial';
}
}
</script>
</html>