繁体   English   中英

如何在图像通过页面上的某个点时更改图像,然后在图像高于该点时将其更改回来?

[英]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()时不会触发滚动事件。 htmlbody的滚动偏移都必须在isHalfwayDown()加在一起,因为不幸的是浏览器不同意哪个元素代表视口。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM