纯 javascript(在 web 浏览器的上下文中)有几个支持良好的函数来访问 dom 元素:
document.getElementById(id);
document.getElementsByTagName(tagName);
此外,现代浏览器支持:
document.getElementsByClassName(className);
如果这些是<li>
文档中唯一的元素,则使用 getElementsByTagName() 并将事件处理程序附加到每个元素是有意义的:
// get 'li' elements
var listElems = document.getElementsByTagName('li');
// create a placeholder for our image
var image = document.createElement('img');
image.style.display = 'none';
image.style.position = 'absolute';
document.body.appendChild(image);
// Arrays have a .forEach() function, but it doesn't work for "NodeList"'s,
// which is what we get from getElementsByTagName().
// We could use Array.prototype.forEach.call(nodelist, callback), but it's not
// always supported, so we write our own.
function each(lst, callback) {
for (var i = 0; i < lst.length; ++i) {
callback(lst[i]);
}
}
// Microsoft tries really hard to allow people to create
// web-sites that break outside Internet Explorer by
// implementing their own function definitions like attachEvent.
// So we have to write silly things like the following:
function addEvent(elem, evt, func) {
if (elem.addEventListener) elem.addEventListener(evt, func);
else if (elem.attachEvent) elem.attachEvent('on' + evt, func);
}
function showImage(event) {
if (event.target.innerHTML.indexOf('event 1') != -1) {
image.src = 'http://ulv.no/ulv.jpg';
} else if (event.target.innerHTML.indexOf('event 2') != -1) {
image.src = 'http://elg.no/elg.jpg';
} else if (event.target.innerHTML.indexOf('event 3') != -1) {
image.src = 'http://sau.no/sau.jpg';
}
// The following code should be wrapped in some checks to keep
// the image from disappearing outside the screen edge when the
// cursor is close to the edge.
image.style.left = event.clientX + 'px';
image.style.top = event.clientY + 'px';
image.style.display = 'block';
}
function hideImage(event) {
image.style.display = 'none';
}
each(listElems, function (elem) {
addEvent(elem, 'mouseover', showImage);
addEvent(elem, 'mouseout', hideImage);
});
JSFiddle
如果您有其他<li>
元素,请考虑为它们提供 id 或类,并使用其他函数之一来枚举元素。当然你也可以使用 jQuery。
$('li').hover(function (event) {
alert('start showing image (' + event.target.innerHTML + ')');
}, function (event) {
alert('hide image (' + event.target.innerHTML + ')');
});
JSFiddle