html
2016-12-11 1 views -1 likes 
-1

나는 html을 배우고 있는데 버튼을 클릭 할 때 이미지를 어떻게 바꿀 수 있는지 알고 싶다. 이것은 내가 아래 지금까지 코드가 무엇 : -버튼을 클릭했을 때 이미지를 변경하는 방법

<button onclick="document.getElementById('myImage').src='https://www.google.co.uk/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png'">change image</button> 
 

 
<img id="myImage" src="https://www.google.co.uk/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" width="800" height="600" longdesc="https://www.google.co.uk/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">

내가 버튼을 클릭하면 이미지를 변경 할 수 있어야합니다. 그럼 이미지가 google이고 버튼을 클릭했을 때 우분투가 나타나고 우분투를 누른 다음 버튼을 클릭하면 firefox가 필요합니다. 여러 단추를 사용하여 작업을 수행했지만 이미지를 변경하는 데 하나의 단추를 사용하는 방법을 모르겠습니다.

누가 도움이된다면 도움이 될 것입니다.

+0

을하고있다, 그것은 단지 당신이 다시 같은 이미지로 이미지를 볼 수 있습니다 대체하고 있어요? –

답변

0

다음은 자바 스크립트를 사용하여 이미지를 전환하는 예입니다. 카운터는 1-3을 통해 실행되고 이에 따라 이미지가 표시됩니다. 각 파트에 대한 설명은 주석을 참조하십시오. 이를 더 많은 이미지로 확장하려면 이미지 배열을 만든 다음 배열 길이가 올 때까지 각 배열을 표시하면서 배열을 증가시켜 배열 시작 부분부터 다시 시작할 수 있습니다. 이 이미지 SRC를 변경 어떻게 당신의 코드가

var x = 1; //initializes counter 
 
function switchImg() { 
 
    if (x == 1) { //if the counter is at 1 
 
    document.getElementById("imgToSwitch").src = "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcR7pz7PYv3YJ1R391uzau_CS-kXxgpWG8zrDtam-LsUK50KEAM4_wIgKg"; 
 
    x++; //increments the counter to 2 
 
    } else if (x == 2) { //if this is the 2nd click 
 
    document.getElementById("imgToSwitch").src = "https://www.mozilla.org/media/img/styleguide/identity/firefox/guidelines-logo.7ea045a4e288.png"; 
 
    x++; //increments counter to 3 
 
    } else if (x == 3) { //if the counter is 3 
 
    document.getElementById("imgToSwitch").src = "https://www.wired.com/wp-content/uploads/2015/09/google-logo-1200x630.jpg"; 
 
    x = 1; //resets counter to 1 
 
    } 
 
}
/*not needed. Just used to make everything pretty. */ 
 

 
body { 
 
    display: flex; 
 
    flex-direction: column; 
 
    justify-content: center; 
 
    align-items: center; 
 
} 
 
img { 
 
    height: 110px; 
 
}
<!--calls the function when it is clicked --> 
 
<button type="button" onclick="switchImg()">Click Me!</button> 
 
<!--image with id of "imgToSwitch." This is the content that is targeted --> 
 
<img src="https://www.wired.com/wp-content/uploads/2015/09/google-logo-1200x630.jpg" id="imgToSwitch">

+1

미안 해요 우분투 로고가 날 트 위치 만들기했다 –

관련 문제