2013-10-11 57 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

欢迎的话,请创建[的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