2014-10-22 2 views
0
<html> 
    <head> 
     <script> 
      function show_function() { 
       var example_image=document.getElementById("example_image"); 
       example_image.src="example_one.png"; 
      } 
      function hide_function() { 
       var example_image=document.getElementById("example_image"); 
       example_image.src="example.png"; 
      } 
     </script> 
    </head> 
<body> 
    <div class="one" onmouseover="show_function()" onmouseout="hide_function()"> 
     <img id="example_image" src="example.png"> 
    </div> 
    <div class="two" onmouseover="show_function()" onmouseout="hide_function()"> 
     <img id="example_image" src="example.png"> 
    </div> 
</body> 
</html> 

첫 번째 div 위에 마우스를 올려 놓으면 이미지가 변경됩니다. 하지만 두 번째 div 위에 마우스를 올리면 첫 번째 div의 이미지도 변경됩니다.여러 요소에서 onmousehover 이벤트를 사용하는 방법?

누구나 자바 스크립트에서만 그것을 수행하는 방법을 알고 있습니까?

+1

ID는 고유 – DaniP

+0

패스'인수로 this'해야? –

+0

"this"를 함수 매개 변수로 전달한 다음 함수 내에서이 요소를 사용하여 원하는 요소/인접 요소를 대상으로 지정합니다. – n1kkou

답변

1

Danko와 마찬가지로 ID는 고유해야합니다.

<html> 
<head> 
<script> 
function show_function(id, hide) 
{ 
    var example_image=document.getElementById(id); 

    if(hide){ 
    example_image.src="example.png"; 
    } else{ 
    example_image.src="example_one.png"; 
    } 
} 
</script> 
</head> 
<body> 
<div class="one" 
onmouseover="show_function('example_image1')" 
onmouseout="show_function('example_image1', true)" /> 
<img id="example_image1" src="example.png"> 
</div> 
<div class="one" 
onmouseover="show_function('example_image2')" 
onmouseout="show_function('example_image2', true)" /> 
<img id="example_image2" src="example.png"> 
</div> 
</body> 
</html> 

또는이 너무 같이 갈 수 있습니다 : 다음 단계는 함수에 변수를 삽입하는 것입니다

<img src="example.png" 
onmouseover="this.src='example_one.png';" 
onmouseout="this.src='example.png';" /> 

는 희망이 도움이!

0

당신은 이런 식으로 작업을 수행 할 수 있습니다

show_function = function (container) { 
    container.childNodes[1].src = "example_one.png"; 
} 
hide_function = function (container) { 
    container.childNodes[1].src = "example.png"; 
} 

다음 HTML에서, 함수에 this를 전달합니다

<div class="one" onmouseover="show_function(this)" onmouseout="hide_function(this)"> 
    <img id="example_image" src="example.png"> 
</div> 
<div class="two" onmouseover="show_function(this)" onmouseout="hide_function(this)"> 
    <img id="example_image" src="example.png"> 
</div> 
0

을 당신이 [0] 사업부의 첫 번째 자식 노드를 원하는 생각합니다. 호버 한 객체를 콜백에 전달합니다.

function show(e){ 
 
    document.getElementById('label').innerHTML = e.children[0].id; 
 
    e.style.border = "solid 2px red"; 
 
    } 
 

 
function hide(e){ 
 
    
 
    e.style.border = "0"; 
 
    
 
    }
<div class="one" onmouseover="show(this)" onmouseout="hide(this)"> 
 
<img id="example_image" src="example.png" class="one" > 
 
</div> 
 
<div class="two" onmouseover="show(this)" onmouseout="hide(this)"> 
 
<img id="example_image" src="example.png" class="two"> 
 
</div> 
 
<p id='label' ></p>

관련 문제