js implements simple examples of fixed advertising effects on the left and right sides

  • 2020-05-26 07:52:16
  • OfStack

This article illustrates a simple way for js to achieve a fixed advertising effect on the right and left. Share with you for your reference. The specific analysis is as follows:

Most websites have fixed advertising space on the left and right sides. The following is the simplest code to achieve this effect. It may cause 1 point jitter when scrolling under ie.

Point 1:


var adtop = adleft.offsetTop;

Get the distance from the top of the element, which you need to use when scrolling.

Point 2:

adleft.style.top=adtop+(document.documentElement.scrollTop || document.body.scrollTop)+"px";
When scrolling, assign the top position of the element to the distance between the element itself and the top plus the scrolling distance.

The code:


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title> Headless document </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> About advertising </h1>
<div id="adleft"> On the left side of advertising </div>
<div id="adright"> On the right side of the advertising </div>
</body>
</html>

I hope this article is helpful for you to design javascript program.


Related articles: