[英]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?
I am completely new to javascript, but I want to learn it rather than jQuery to get some fundamental knowledge. 我是javascript的新手,但我想学习它而不是jQuery来获得一些基础知识。 The function I want to create should animate an arrow to turn upwards when it passes 50% of the page.
我想要创建的函数应该在箭头通过页面的50%时动画向上转动。 In addition to this, the function that it calls when upside down should change.
除此之外,倒置时调用的功能应该改变。
So: upArrow onClick(scrollUp) downArrow onClick(scrollDown) 所以:upArrow onClick(scrollUp)downArrow onClick(scrollDown)
I'm sure I sound stupid, but maybe someone can understand what I'm trying to explain. 我确定我听起来很愚蠢,但也许有人能理解我想要解释的内容。
You can either write the imageelement.src
property to point to a different arrow, or, for extra smoothness, use a CSS sprite containing both arrows and write element.style.backgroundPosition
to change the displayed image without having to load a new image. 您可以将
imageelement.src
属性写入指向不同的箭头,或者,为了获得额外的平滑度,请使用包含两个箭头的CSS sprite和write element.style.backgroundPosition
来更改显示的图像,而无需加载新图像。
You can assign a new function to imageelement.onclick
to change what happens when you click on it, but usually it is simpler to have one click-function that decides what to do based on state. 您可以为
imageelement.onclick
指定一个新功能,以更改单击它时发生的情况,但通常只需一个单击功能即可根据状态决定做什么。
eg: 例如:
<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;
}
Browser compatibility notes: window.onscroll()
is because IE doesn't fire the scroll event when scrollTo()
is used. 浏览器兼容性说明:
window.onscroll()
是因为IE在使用scrollTo()
时不会触发滚动事件。 Both html
and body
's scroll offsets have to be added together in isHalfwayDown()
because the browsers unfortunately don't agree on which element represents the viewport. html
和body
的滚动偏移都必须在isHalfwayDown()
加在一起,因为不幸的是浏览器不同意哪个元素代表视口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.