2013-10-11 6 views
-1

У меня есть меню с изображениями. Скажем, это изображения. Когда я наводил верх, он меняется на второе изображение. Я хочу, чтобы второе изображение оставалось, когда я нажимаю на него (когда он активен).Изменение изображения при нажатии

<a href='index.html'> 
    <span> 
    <img src="http://cdn.arstechnica.net/wp-content/uploads/2012/10/06_Place_20773_1_Mis.jpg" onmouseover="this.src='http://s3.firstpost.in/wp-content/uploads/2012/12/1Christmas_GettyImages.jpg'" onmouseout="this.src='http://cdn.arstechnica.net/wp-content/uploads/2012/10/06_Place_20773_1_Mis.jpg'"/> 
    </span> 
</a> 

http://jsfiddle.net/nDkRG

+0

Добро пожаловать на SO, пожалуйста, создайте [jsFiddle] (http://jsfiddle.net/), чтобы заставить людей, чтобы помочь вам. –

+0

Почему люди стремятся? - Я знаю, что объяснение не понятно, но я предполагаю, что английский язык не первый. –

ответ

1

В простом JavaScript (дав изображение id, легко предназначаться его):

/* called by clicking the link (because the image is a child-element), 
    a simple means of preventing the default action: */ 
function nothing (e){ 
    e.preventDefault(); 
} 

// the 'event' itself is passed as the first argument to the function 
function update (e){ 
    // find what the event-type is ('click','mouseover', 'mouseout'): 
    switch (e.type){ 
     // if it was the mouseover event, we: 
     case 'mouseover': 
      /* update the src property, retrieving the new src from the 
       custom data-over attribute of the element: 
      */ 
      this.src = this.getAttribute('data-over'); 
      // break out of the switch: 
      break; 
     case 'mouseout': 
      // if the image doesn't contain the 'clicked' class-name, we: 
      if (!this.classList.contains('clicked')){ 
       /* change the src to the string stored within the custom 
        data-out attribute: 
       */ 
       this.src = this.getAttribute('data-out'); 
      } 
      // break out of the switch: 
      break; 
     // if it's the 'click' event: 
     case 'click': 
      /* we add the 'clicked' class if it's not already there, 
       and remove it if it is already there: 
      */ 
      this.classList.toggle('clicked') 
      break; 
    } 
} 

/* retrieving the relevant image element (by its id, using querySelector 
    and CSS-notation: 
*/ 
var image = document.querySelector('#demo'), 
// retrieving all the 'a' elements, then selecting only the first: 
    link = document.getElementsByTagName('a')[0]; 

// binding an event-handler to the image for the various events: 
image.addEventListener('click', update); 
image.addEventListener('mouseover', update); 
image.addEventListener('mouseout', update); 

// binding an event-handler to the 'a' element, to handle the 'click' event: 
link.addEventListener('click', nothing); 

JS Fiddle demo.

+1

+1 Вы единственный, кто действительно опубликовал чистое решение для JavaScript. Не знаю, почему все остальные решили использовать jQuery. Вопрос не помечен jQuery, он помечен javascript, и OP не упоминает jQuery. –

-1

пытаются добавить

$('a').click(function(e){ 
    e.preventDefault(); 
    $('img').removeAttr('onmouseover').removeAttr('onmouseout'); 
}) 

обновленный your fiddle

+0

, кто отказался от этого? он делает именно то, что задает вопрос ... по крайней мере, с некоторым комментарием ... – webduvet

Смежные вопросы