![](/img/trans.png)
[英]How can I make text change when a page is scrolled to a certain point using jQuery?
[英]How do I change an image when it passes a certain point on a page, and then change it back when it is above that point?
我是javascript的新手,但我想學習它而不是jQuery來獲得一些基礎知識。 我想要創建的函數應該在箭頭通過頁面的50%時動畫向上轉動。 除此之外,倒置時調用的功能應該改變。
所以:upArrow onClick(scrollUp)downArrow onClick(scrollDown)
我確定我聽起來很愚蠢,但也許有人能理解我想要解釋的內容。
您可以將imageelement.src
屬性寫入指向不同的箭頭,或者,為了獲得額外的平滑度,請使用包含兩個箭頭的CSS sprite和write element.style.backgroundPosition
來更改顯示的圖像,而無需加載新圖像。
您可以為imageelement.onclick
指定一個新功能,以更改單擊它時發生的情況,但通常只需一個單擊功能即可根據狀態決定做什么。
例如:
<div id="arrow" class="arrow-down"></div>
#arrow {
position: fixed; top: 0; left: 0; z-index: 10;
width: 32px; height: 32px;
background-image: url(/img/arrow.png);
}
.arrow-down {
background-position: 0 0;
}
.arrow-up {
background-position: 0 -32px;
}
var arrow= document.getElementById('arrow');
window.onscroll=window.onresize= function() {
arrow.className= isHalfwayDown()? 'arrow-up' : 'arrow-down';
};
arrow.onclick= function() {
var h= document.documentElement.scrollHeight;
scrollTo(0, isHalfwayDown()? 0 : h);
window.onscroll();
};
function isHalfwayDown() {
var y= document.documentElement.scrollTop+document.body.scrollTop;
var h= document.documentElement.scrollHeight;
return y>=h/2;
}
瀏覽器兼容性說明: window.onscroll()
是因為IE在使用scrollTo()
時不會觸發滾動事件。 html
和body
的滾動偏移都必須在isHalfwayDown()
加在一起,因為不幸的是瀏覽器不同意哪個元素代表視口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.