您可以尝试德里克的答案,但你很快就会发现,querySelector不怪癖模式或IE 7和更低的IE8的支持,那addEventListener不会被IE 8支持并且更低。
选择为纯JS包括编写自己的getElementsByClassName方法功能(不是特别困难),或使用事件委派让你连接只有一个监听器为每个事件,需要一个简单的hasClass功能。
总之,这里是一个例子:
任何javscripter应该在图书馆或能够在几分钟到代码的一些标准库函数:
// Minimalist addEvent function, ok for the current web
function addEvent(el, fn, evt) {
if (el.addEventListener) {
el.addEventListener(evt, fn, false)
} else if (el.attachEvent) {
el.attachEvent('on' + evt, fn);
}
}
// Returns true or false depending on whether element el has class classname
function hasClassname(el, classname) {
var re = new RegExp('(^|\\s)' + classname + '(\\s|$)');
return re.test(el.className);
}
做的工作的函数:
// Toggle the id. Note that this deals with the case where
// the element to toggle isn't found to prevent errors being thrown
function toggleId(e) {
e = e || window.event;
var el = e.target || e.srcElement;
var o;
if (hasClassname(el, 'tomouseover')) {
if (e.type == 'mouseover') {
o = document.getElementById('set1');
if (o) o.id = 'set2';
} else if (e.type == 'mouseout') {
o = document.getElementById('set2');
if (o) o.id = 'set1';
}
}
}
// Attach the listener onload, could also add from a bottom
// script or inline. If inline, use `toggleId(event)`
window.onload = function() {
addEvent(document.body, toggleId, 'mouseover');
addEvent(document.body, toggleId, 'mouseout');
}
以上将在所有的浏览器回IE6和NN 3左右,并将继续在未来的浏览器是要么W3C或IE事件模型的工作。
你可以使用jQuery吗? –
我不喜欢。这是在Google小工具中。如果我不得不去,我可以。 – Wagtail