Home >Web Front-end >JS Tutorial >js implementation of simple left and right fixed advertising effect examples_javascript skills

js implementation of simple left and right fixed advertising effect examples_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:05:011337browse

The example in this article describes how to achieve a simple fixed advertising effect on the left and right sides using js. Share it with everyone for your reference. The specific analysis is as follows:

Most websites have fixed advertising spaces on the left and right sides. The following is the simplest code to achieve this effect. There may be a little jitter when scrolling under IE. This problem will be solved later. Let’s implement it first.

Point 1:

var adtop = adleft.offsetTop;

Get the position of the element from the top, which is needed when scrolling.

Point 2:

Copy code The code is as follows:
adleft.style.top=adtop (document.documentElement. scrollTop || document.body.scrollTop) "px";
When scrolling, the value assigned to the top position of the element is the distance between the element itself and the top plus the scrolling distance.

Above code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>无标题文档</title>
<style>
body{margin:0; padding:0}
#adleft,#adright{
width:30px;
height:100px;
padding:20px;
font:14px/20px arial;
text-align:center;
background:#06c;
position:absolute;
cursor:pointer;
color:#fff
}
#adleft{left:0; top:150px; }
#adright{right:0; top:150px;}
</style>
<script>
window.onload = function(){
 var adleft = document.getElementById("adleft");
 var adright = document.getElementById("adright");
 var adtop = adleft.offsetTop;
 window.onscroll = function(){
  adleft.style.top = adtop + (document.documentElement.scrollTop || document.body.scrollTop) +"px"; 
  adright.style.top = adtop + (document.documentElement.scrollTop || document.body.scrollTop) +"px"; 
 }
} 
</script>
</head>
<body style="height:2000px;">
<h1>左右广告</h1>
<div id="adleft">左边广告</div>
<div id="adright">右边广告</div>
</body>
</html>

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn