2017-03-14 1 views
0

html 내부의 이미지로 스크롤 높이에 따라 이미지를 변경하려면 어떻게해야합니까?스크롤 할 때의 HTML img src 변경

현재

스크롤에 원하는
<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; 
} 

현재 자바 스크립트 (원하는 높이에 고정 된 이미지의 위치를 ​​변경)

window.onscroll = function(){ 

    if(window.scrollY >= 1000) { 
     document.getElementById('astronaut').setAttribute(
     "style", "position:fixed;"); 
    }else { 
     document.getElementById('astronaut').setAttribute(
     "style", ""); 
    } 

}; 

답변

0
window.onscroll = function(){ 

    if(window.scrollY >= 1000) { 
     document.getElementById("astronaut").src="../img/astronaut-travel.svg"; 
    }else { 
     document.getElementById("astronaut").src="../img/astronaut.svg"; 
    } 

}; 
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>