
* {
margin: 0;
padding: 0;
}
img {
position: absolute;
left: 0;
}
p {
text-align: center;
line-height: 40px;
}
<img src="images/left_ad.png" alt="">
<p>我是正文1</p>
<p>我是正文2</p>
<p>我是正文3</p>
<p>我是正文4</p>
<p>我是正文5</p>
<p>我是正文6</p>
<p>我是正文7</p>
<p>我是正文8</p>
<p>我是正文9</p>
<p>我是正文10</p>
<p>我是正文11</p>
<p>我是正文12</p>
<p>我是正文13</p>
<p>我是正文14</p>
<p>我是正文15</p>
<p>我是正文16</p>
<p>我是正文17</p>
<p>我是正文18</p>
<p>我是正文19</p>
<p>我是正文20</p>
<p>我是正文21</p>
<p>我是正文22</p>
<p>我是正文23</p>
<p>我是正文24</p>
<p>我是正文25</p>
<p>我是正文26</p>
<p>我是正文27</p>
<p>我是正文28</p>
<p>我是正文29</p>
<p>我是正文30</p>
<p>我是正文31</p>
<p>我是正文32</p>
<p>我是正文33</p>
<p>我是正文34</p>
<p>我是正文35</p>
<p>我是正文36</p>
<p>我是正文37</p>
<p>我是正文38</p>
<p>我是正文39</p>
<p>我是正文40</p>
<p>我是正文41</p>
<p>我是正文42</p>
<p>我是正文43</p>
<p>我是正文44</p>
<p>我是正文45</p>
<p>我是正文46</p>
<p>我是正文47</p>
<p>我是正文48</p>
<p>我是正文49</p>
<p>我是正文50</p>
//1.拿到需要操作的元素
const oAdImg = document.querySelector("img");
//2.計算廣告圖片top的值=(視口高度-廣告高度)/2
const screenHeight = getScreen().height;
const imgHeight = oAdImg.offsetHeight;
const offsetY = (screenHeight - imgHeight) / 2;
// console.log(offsetY);
//3.將計算之后的top值,設定給廣告圖片
// oAdImg.style.top = offsetY + 'px';
easeAnimation(oAdImg, {
"top": offsetY
});
//4.監聽網頁的滾動事件
window.onscroll = function() {
//獲取到網頁滾動的距離
//廣告圖片top的值+網頁滾動的距離
let pageOffsetY = getPageScroll().y;
easeAnimation(oAdImg, {
"top": offsetY + pageOffsetY
});
};
// 瀏覽器視口寬高
function getScreen() {
let width, height;
if (window.innerWidth) {
width = window.innerWidth;
height = window.innerHeight;
} else if (document.compatMode === "BackCompat") {
width = document.body.clientWidth;
height = document.body.clientHeight;
} else {
width = document.documentElement.clientWidth;
height = document.documentElement.clientHeight;
}
return {
width: width,
height: height
}
}
// 緩動影片
function easeAnimation(ele, obj, fn) {
clearInterval(ele.timerId);
ele.timerId = setInterval(function() {
// flag變數用于標記是否所有的屬性都執行完了影片
let flag = true;
for (let key in obj) {
let target = obj[key];
// 1.拿到元素當前的位置
let style = getComputedStyle(ele);
let begin = parseInt(style[key]) || 0;
// 2.定義變數記錄步長
// 公式: (結束位置 - 開始位置) * 緩動系數(0 ~1)
let step = (target - begin) * 0.3;
// 3.計算新的位置
begin += step;
if (Math.abs(Math.floor(step)) > 1) {
flag = false;
} else {
begin = target;
}
// 4.重新設定元素的位置
ele.style[key] = begin + "px";
}
//判斷影片是否執行完
if (flag) {
//影片執行完后關閉定時器
clearInterval(ele.timerId);
//判斷是否傳入fn函式,有才執行反之不執行
fn && fn();
}
}, 100);
}
// 網頁滾動距離
function getPageScroll() {
let x, y;
if (window.pageXOffset) {
x = window.pageXOffset;
y = window.pageYOffset;
} else if (document.compatMode === "BackCompat") {
x = document.body.scrollLeft;
y = document.body.scrollTop;
} else {
x = document.documentElement.scrollLeft;
y = document.documentElement.scrollTop;
}
return {
x: x,
y: y
}
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/352251.html
標籤:其他
上一篇:“21天好習慣”第一期-1 JavaScript實作倒計時
下一篇:根據實時下拉串列過濾資料值
