どうぞhttp://jsfiddle.net/5U9w9/2/
コメントを追加して jsFidle を更新し、ここのリンクも更新します。
JavaScript
// grab all the required element on the page
var img_all = document.getElementsByTagName('img');
// for every element do this
for (i=0; i< img_all.length; i++){
var img = img_all[i];
// set the required event on the element
// when the event of the element occurs, the associated function will be called with event object as it's argument.
// https://developer.mozilla.org/en-US/docs/Mozilla_event_reference
//img.addEventListener('mouseover', mouseover_handler, false);
AddEvent(img, 'mouseover', mouseover_handler)
//mouseout_handler will be called, on mouseout event
// img.addEventListener('mouseout', mouseout_handler, false);
AddEvent(img, 'mouseout', mouseout_handler)
}
function mouseover_handler(e){
// el is and event object and has various properties like clientX, clientY, srcElement, etc. you can check them by console.log(el)
console.log(e)
// to get the element i'm hovering, use
var element = e.srcElement;
//element is DOM element and can be manupulated
element.style.width="100px";
}
// similarly handler for an another event.
function mouseout_handler(e){
e.srcElement.style.width="50px";
}
// cross-browser addEventListner
function AddEvent(html_element, event_name, event_function)
{
if(html_element.attachEvent) //Internet Explorer
html_element.attachEvent("on" + event_name, function() {event_function.call(html_element);});
else if(html_element.addEventListener) // Everything else
html_element.addEventListener(event_name, event_function, false);
}
アップデート
AddEvent
IE サポートの代わりに使用しaddEventListner()
ます。 (CREDIT: @James Hill の回答)