在這裏,我們去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
在addEventListner()
的地方IE支持。(來源:@詹姆斯希爾的回答)
任何異議使用JQuery? – webnoob
你是否有相同的功能應用於每個圖像? – Saurabh
@webnoob,讓我休息一下。 jQuery沒有被標記。 jQuery和JS並不是同義詞。 –