Queque JavaScript to get the position of an element

JavaScript get the position of an element

Sunday , April 22, 2018

Specific content

Question: How to make the ad image position stay in a fixed position

1.     Get the initial position

2.     Page scroll event record position value

3.     Initial position value + distance value after moving = the position where the picture should be now

4.     Run the page scroll event

For example:

<!DOCTYPE html>
<
html lang="en">
<
head>
    <
meta charset="UTF-8">
    <
title>广告图片固定位置</title>
    <
style type="text/css">#main{text-align:center; width:1014px; margin: 0 auto;}#adver{position:absolute;left
       

       

           

           
:10px;
           
top:30px;
           
z-index:2;
        }
    </
style>
</
head>
<
body>
<
div id="adver">
    <
img src="images/adv.jpg"/>
</
div>
<
div id="main">
    <
img src="images/main1.jpg"/>
    <
img src="images/main2.jpg"/>
    <
img src= "images/main3.jpg" />
</
div >
<
script > var adverTop ;   // record the position of the initial Top value var adverLeft ;   // record the position of the initial Left value var adverObject = document . getElementById ( "adver" ); function init () { // If the currentStyle value exists, it means IE browser if ( adverObject . currentStyle ){
   

   

   



   

       

       

           
// Initialize the value of the vertex value of the ad image (IE browser )
           
adverTop = parseInt ( adverObject . currentStyle . top );
           
// Initialize the left value of the ad image (IE browser )
           
adverLeft = parseInt ( adverObject . currentStyle . left ) ;
        }
else {
           
// Initialize the vertex value of the ad image ( normal browser )
           
adverTop = parseInt ( document . defaultView . getComputedStyle(adverObject,null).top);
           
//初始化广告图片的左边的值(普通浏览器)
           
adverLeft = parseInt(document.defaultView.getComputedStyle(adverObject,null).left);
           
        } 
    }
   
/**
     *
广告图片移动方法
     */
   
function move() {
       
//取得初始Top
       
var sTop = parseInt(document.documentElement.scrollTop || document.body.scrollTop);
       
//取得初始Left
       
var sLeft = parseInt(document.documentElement.scrollLeft || document.body.scrollLeft);
       
//需要用初始值加上滚动后的值
       
adverObject.style.top = adverTop+sTop +"px";
       
adverObject.style.left = adverLeft+sLeft +"px";
    }
   
   
//页面加载事件
   
window.onload = init;
   
//页面滚动事件
   
window.onscroll = move;
</
script>
</
body>
</
html>

 

元素属性应用

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324636294&siteId=291194637