Home >Web Front-end >JS Tutorial >Use js to fix the picture at a certain position on the screen!
Idea:
1. Get the distance of the object from the top and left side;
2. Get the element object;
3. Get the distance of the scroll bar when the scroll bar scrolls;
4. Scroll bar The function is executed when scrolling: the distance of the object from the top/left side becomes the original distance from the top/left side by the number of pixels scrolled by the scroll bar.
html code:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="left"> <img src="images/z1.jpg" alt=""/> </div> <div id="right"> <img src="images/z2.jpg" alt=""/> </div> </body> </html>
css code:
*{ margin: 0; padding: 0; } body{ width: 2000px; height: 2000px; } .left{ position: absolute; width: 110px; height: 110px; top: 100px; left: 50px; } .right{ position: absolute; width: 110px; height: 110px; top: 100px; left: 1360px; }
js code:
var leftT;//左侧p距离顶部距离 var leftL;//左侧p距离左侧距离 var rightT;//右侧p距离顶部距离 var rightL;//右侧p距离左侧距离 var objLeft;//左侧p文档对象 var objRight;//右侧p文档对象 function place(){ objLeft=document.getElementById("left"); objRight=document.getElementById("right"); leftT=document.defaultView.getComputedStyle(objLeft,null).top; leftL=document.defaultView.getComputedStyle(objLeft,null).left; rightT=document.defaultView.getComputedStyle(objRight,null).top; rightL=document.defaultView.getComputedStyle(objRight,null).left; } //获取滚动条滚动的像素数 function move(){ var scrollT=document.documentElement.scrollTop; var scrollL=document.documentElement.scrollLeft; //设置左侧p距离顶部的像素 objLeft.style.top=parseInt(leftT)+scrollT+"px"; objLeft.style.left=parseInt(leftL)+scrollL+"px"; objRight.style.top=parseInt(rightT)+scrollT+"px"; objRight.style.left=parseInt(rightL)+scrollL+"px"; } window.onload=place; window.onscroll=move;
Related recommendations: [JavaScript video tutorial]
The above is the detailed content of Use js to fix the picture at a certain position on the screen!. For more information, please follow other related articles on the PHP Chinese website!