如何使用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", "");
}
};
答案 0 :(得分:0)
window.onscroll = function(){
if(window.scrollY >= 1000) {
document.getElementById("astronaut").src="../img/astronaut-travel.svg";
}else {
document.getElementById("astronaut").src="../img/astronaut.svg";
}
};
答案 1 :(得分:0)
<!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>