当其中一个被隐藏时,突出显示具有相同类别的所有元素 [英] Highlight all elements with same class when one of them is moused over

查看:114
本文介绍了当其中一个被隐藏时,突出显示具有相同类别的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,当它们中的一个被隐藏时,是否可以使用相同的类高亮显示所有项目?

例如,如果我有两个段落class p1 和两个段落与类 p2 ,我希望 p1 在鼠标悬停时突出显示,我还希望鼠标悬停时突出显示p2的两个元素。

 < p class =p1>这应该在鼠标悬停时突出显示< / p> 
< p class =p2>这应该在鼠标悬停时突出显示< / p>
< p class =p1>这应该在鼠标悬停时突出显示< / p>
< p class =p2>这应该在鼠标悬停时突出显示< / p>


解决方案

我不禁感到这个应该更简洁(使用 3 for(...)循环感觉不必要的昂贵),但是一种方法是:

  Object.prototype.classHighlight = function(over,out){
var that = this.length?这:[this];
函数onOver(){
for(var i = 0,len = that.length; i< len; i ++){
that [i] .style.backgroundColor = over;


函数onOut(){
for(var i = 0,len = that.length; i< len; i ++){
that [ i] .style.backgroundColor = out;
}
}
for(var i = 0,len = that.length; i< len; i ++){
that [i] .onmouseover = onOver;
that [i] .onmouseout = onOut;
}
};

document.getElementsByClassName('test')。classHighlight('#f90','#fff');

JS Fiddle演示


In JavaScript, is it possible to highlight all items with the same class when one of them is moused over?

For example, if I had two paragraphs with the class p1 and 2 paragraphs with the class p2, I'd want both elements of p1 to be highlighted on mouseover, and I'd also want both elements of p2 to be highlighted on mouseover.

<p class = "p1">This should be highlighted on mouseover</p>
<p class = "p2">This should be highlighted on mouseover</p>
<p class = "p1">This should be highlighted on mouseover</p>
<p class = "p2">This should be highlighted on mouseover</p>

解决方案

I can't help but feel this should be more concise (the use of three for (...) loops feels unnecessarily expensive), but one approach:

Object.prototype.classHighlight = function (over, out) {
    var that = this.length ? this : [this];
    function onOver() {
        for (var i = 0, len = that.length; i < len; i++) {
            that[i].style.backgroundColor = over;
        }
    }
    function onOut() {
        for (var i = 0, len = that.length; i < len; i++) {
            that[i].style.backgroundColor = out;
        }
    }
    for (var i = 0, len = that.length; i < len; i++) {
        that[i].onmouseover = onOver;
        that[i].onmouseout = onOut;
    }
};

document.getElementsByClassName('test').classHighlight('#f90', '#fff');

JS Fiddle demo.

这篇关于当其中一个被隐藏时,突出显示具有相同类别的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆