开发者

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. The function 开发者_如何学GoI want to create should animate an arrow to turn upwards when it passes 50% of the page. In addition to this, the function that it calls when upside down should change.

So: 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.

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.

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. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜