[英]Changing HTML img src on scroll
如何使用html內的圖像更改取決於滾動高度的圖像?
當前
<div id="astronaut">
<img src="img/astronaut.svg" alt="Astronaut Static" />
</div>
滾動所需
<div id="astronaut">
<img src="img/astronaut-travel.svg" alt="Astronaut Travelling" />
</div>
當前CSS(居中圖片)
#astronaut {
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 100;
}
當前的JavaScript(將圖像的位置更改為所需的高度)
window.onscroll = function(){
if(window.scrollY >= 1000) {
document.getElementById('astronaut').setAttribute(
"style", "position:fixed;");
}else {
document.getElementById('astronaut').setAttribute(
"style", "");
}
};
window.onscroll = function(){
if(window.scrollY >= 1000) {
document.getElementById("astronaut").src="../img/astronaut-travel.svg";
}else {
document.getElementById("astronaut").src="../img/astronaut.svg";
}
};
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$( document ).ready(function() {
window.onscroll = function(){
if(window.scrollY >= 100) {
document.getElementById('astronaut').setAttribute(
"style", "position:fixed;");
$('#astronaut img').attr('src', 'https://upload.wikimedia.org/wikipedia/commons/thumb/3/37/Small-world-network-example.png/220px-Small-world-network-example.png')
}else {
document.getElementById('astronaut').setAttribute(
"style", "");
}
};
});
</script>
<style>
#astronaut {
background:red;
height:1050px;
z-index: 100;
}
</style>
</head>
<body>
<div id="astronaut">
<img src="http://www.mathcurve.com/polyedres/archimedien/pavage-sphere-dodecaedreTronque.jpg" alt="Astronaut Static" />
</div>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.