在悬停时更改img标记内容

时间:2014-11-22 22:58:34

标签: javascript css image mouseover

我正在尝试使用鼠标悬停在顶部时更改<img>标记。问题是,我有相同的图片。

我的HTML看起来像这样:

<img id="my-img" src=".../wp-content/uploads/2014/01/DSC04543-2.jpg" onmouseover="hover(this);" onmouseout="unhover(this);" />

我的JavaScript看起来像这样:

function hover(element) {
    element.setAttribute('src', '.../wp-content/uploads/2014/11/DSC04543.jpg');
}
function unhover(element) {
    element.setAttribute('src', '.../wp-content/uploads/2014/01/DSC04543-2.jpg');
}  

我正在关注这个帖子,但没有得到任何积极的结果。图像显示正常,但我看不到任何悬停效果: CSS: Change image src on img:hover

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

一种方法如下:

// e is the Event object, passed in by addEventListener:
function hoverToggle(e) {
  // e.target is the element that triggered the event:
  var el = e.target;
  if (e.type === 'mouseenter') {
    // we set the src to the 'data-hoversrc' attribute-value:
    el.src = el.dataset.hoversrc;
  } else if (e.type === 'mouseleave') {
    // we set the src to the 'data-originalsrc' attribute-value:
    el.src = el.dataset.originalsrc;
  }
}

// getting a reference to the specific image:
var demoImage = document.querySelector('#demo');

// adding event-listeners for the 'mouseenter' (hover), 
// and 'mouseleave' (unhover) events:
demoImage.addEventListener('mouseenter', hoverToggle);
demoImage.addEventListener('mouseleave', hoverToggle);

function hoverToggle(e) {
  var el = e.target;
  if (e.type === 'mouseenter') {
    el.src = el.dataset.hoversrc;
  } else if (e.type === 'mouseleave') {
    el.src = el.dataset.originalsrc;
  }
}

var demoImage = document.querySelector('#demo');

demoImage.addEventListener('mouseenter', hoverToggle);
demoImage.addEventListener('mouseleave', hoverToggle);
<img id="demo" src="http://lorempixel.com/300/300/nature/1" data-originalsrc="http://lorempixel.com/300/300/nature/1" data-hoversrc="http://lorempixel.com/300/300/nature/2" />

参考文献: