我想在我徘徊的所有元素中添加类。但我使用的是jquery代码。但当我悬停在任何元素类上时会自动添加所有父级,任何人都可以建议我如何在元素中添加我实际上徘徊的类。
我的js代码是
$(AllTags).mouseover(function(e){
e.stopPropagation();
$(this).addClass('g-hovered');
});
$(AllTags).mouseenter(function(e){
e.stopPropagation();
$(this).removeClass('g-hovered');
});
var AllTags = "div, span, applet, object, iframe,h1, h2, h3, h4, h5, h6, p, blockquote, pre,a, abbr, acronym, address, big, cite, code,del, dfn, em, img, ins, kbd, q, s, samp,small, strike, strong, sub, sup, tt, var,b, u, i, center,dl, dt, dd, ol, ul, li,fieldset, form, label, legend,table, caption, tbody, tfoot, thead, tr, th, td,article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary,time, mark, audio, video,article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section "
我不想传递任何特定的类和标记。
答案 0 :(得分:1)
看看这个小提琴。这是你想要实现的目标吗?
var allTags = "div, span, applet, object, iframe,h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code,del, dfn, em, img, ins, kbd, q, s, samp,small, strike, strong, sub, sup, tt, var,b, u, i, center,dl, dt, dd, ol, ul, li,fieldset, form, label, legend,table, caption, tbody, tfoot, thead, tr, th, td,article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary,time, mark, audio, video,article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section";
$(allTags).on('mouseover', function(e) {
e.stopPropagation();
$(this).addClass('g-hovered');
});
答案 1 :(得分:1)
以下是使用javascript完成的操作:Demo
var allTags = ['div', 'span', 'applet', 'object', 'iframe','h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'blockquote', 'pre', 'a', 'abbr', 'acronym', 'address', 'big', 'cite', 'code','del', 'dfn', 'em', 'img', 'ins', 'kbd', 'q', 's', 'samp','small', 'strike', 'strong', 'sub', 'sup', 'tt', 'var','b', 'u', 'i', 'center','dl', 'dt', 'dd', 'ol', 'ul', 'li','fieldset', 'form', 'label', 'legend','table', 'caption', 'tbody', 'tfoot', 'thead', 'tr', 'th', 'td','article', 'aside', 'canvas', 'details', 'embed', 'figure', 'figcaption', 'footer', 'header', 'hgroup', 'menu', 'nav', 'output', 'ruby', 'section', 'summary','time', 'mark', 'audio', 'video','article', 'aside', 'details', 'figcaption', 'figure', 'footer', 'header', 'hgroup', 'menu', 'nav', 'section'];
var j=0;
window.onmouseover = function() {
change();
};
function classAdd(element) {
return function() { element.setAttribute('class','first');
};
}
function classRemove(element) {
return function() { element.removeAttribute('class','first');
};
}
function change() {
for (var i=0; i<allTags.length; i++) {
var element=document.getElementsByTagName(allTags[i]);
for (j=0;j<element.length;j++) {
element[j].onmouseover = classAdd(element[j]);
element[j].onmouseout = classRemove(element[j]);
}
}
}