JS Simple way to keep DIV fixed relative to the browser

  • 2021-06-28 11:18:07
  • OfStack

This article provides an example of how JS can simply implement DIV in a fixed position relative to the browser.Share it for your reference, as follows:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>Anchor Properties</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta content="noindex, nofollow" name="robots">
<script>
function Totop(){
  window.scrollTo(0,0);
}
function bottom(){
  //scrollHeight Property is to get the scrolling height of the object. 
  window.scrollTo(0,document.body.scrollHeight);
}
function left(){
  //alert("left");alert(document.body.scrollLeft)
  var left = 0-document.body.scrollWidth;// Pixels moved to the left 
  window.scrollBy(left,0 );
}
function right(){
  //alert(document.body.scrollWidth);
  // Width of the entire scrollbar 
  window.scrollBy(document.body.scrollWidth,0);
}
function init(){
  var init_pos=oLayer.style.posTop ;
  var init_left=oLayer.style.posLeft;
  document.body.onscroll=function(){
  //document.body.scrollTop Equals the distance from the start of the scroll to the upper end of the scroll slider 
    oLayer.style.posTop=document.body.scrollTop+init_pos;
  //scrollLeft Sets or gets the distance between the left edge of the object and the leftmost end of the currently visible content in the window 
    oLayer.style.posLeft=document.body.scrollLeft +init_left;
  }
}
</script>
</head>
<body onload="init()">
<a onclick="bottom()"> Bottom setting </a>
<div id="oLayer" style="position:absolute;left:120;top:60;z-index:2;background:green;width:120px;height:120px"> ddddd
</div>
<br>
<a onclick="right()"> Location &nbsp; right </a>
<div style="width:1500px;height:30px;float:left">width="2000px"</div>
<a style="float:right" onclick="left()"> Location &nbsp; Left </a>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><a onclick="Totop()"> Location &nbsp; top </a>
</body>
</html>

More readers interested in JavaScript related content can view this site's topics: JavaScript Switching Special Effects and Techniques Summary, JavaScript Finding Algorithmic Techniques Summary, JavaScript Animation Special Effects and Techniques Summary, JavaScript Errors and Debugging Techniques Summary, JavaScript Data Structure and Algorithmic Techniques Summary,Summary of JavaScript Traversal Algorithms and Techniques and Summary of JavaScript Mathematical Operation Usage

I hope that the description in this paper will be helpful to everyone's JavaScript program design.


Related articles: