Use js to fix the picture at a certain position on the screen!

藏色散人
Release: 2022-08-07 10:47:44
forward
2213 people have browsed it

Use js to get the scroll bar scrolling distance and 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:

     
Copy after login

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; }
Copy after login

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;
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!