侧边栏广告就是指我们在浏览网站的时候在网页的右边中间部分显示的那个div,无论我们是拖动滚动条,还是放大缩小窗口,广告始终显示在右边的中间。这里主要是提供两种方法的实现。
方法一:
就是使用纯粹的布局来实现,比较简单,即是使用 position:fixed; 没有什么好说的直接看代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>侧边栏广告</title>
<style>
div {
width: 100px;
height: 100px;
background-color: red;
position: fixed;/** 最简单的一种是新方法,就是让绝对定位设置成固定,但是IE6不会支持此种特性*/
right: 0;
top: 50%;
margin-top: -50px;
}
</style>
</head>
<body style="height: 2000px">
<div id="div1">
</div>
</body>
</html>
方法二:
通过设置div top值的方式来实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>侧边栏广告效果2-</title>
<style>
#div1 {
height: 100px;
width: 100px;
background-color: red;
position: absolute;
right: 0px;
}
/**
通过设置div的top值 = scrolltop 的高度 + (可视化区域的高度-div自身的高度)/2 来实现 div始终位于区域中间位置
*/
</style>
<script>
window.onresize=window.onscroll= window.onload=function () {
var oDiv=document.getElementById("div1");
var scrollTop =document.documentElement.scrollTop;
var t = (document.documentElement.clientHeight-oDiv.offsetHeight)/2;
oDiv.style.top=scrollTop+t+"px";
}
</script>
</head>
<body style="height: 2000px;">
<div id="div1">
</div>
</body>
</html
参考自:妙味课堂的原创js视频。