简体   繁体   English

如何使用JavaScript切换元素的不透明度

[英]How to toggle the opacity of Elements using javascript

I have a div which has 14 child divs with some content. 我有与一些内容14周孩子的div一个div。 Now what I need is that, onload it should display all the 14 divs with opacity = 1, but when I mouse over one of them, the opacity of others should reduce by 50%. 现在我需要的是,为onload它应该显示所有14周的div不透明= 1,但是当我鼠标放在其中的一个,其他的不透明度应减少50%。 Only the current one should have the full opacity. 只有当前一个应该有充分的透明度。 Similarly when I move my mouse over another div now, then except the current one, opacity of other divs should be reduced by 50%. 同样,当我现在将我的鼠标移到另一个div那么除了当前,其他的div的不透明度应减少50%。

How can I do so using javascript and I don't want to use any library (jquery). 我怎么能这样做使用JavaScript和我不希望使用任何库(jQuery的)。

Update : Got it working! 更新:得到它的工作! :) :)

/*onmouseover*/
function showCurrentDimOthers(el) {
        var otherElements = document.getElementById("see_all_content_holder").childNodes;
        for (var o = 0; o < otherElements.length; o++) {
            otherElements[o].style.opacity = 0.5;
            otherElements[o].style.filter = 'alpha(opacity=5)';
        }

        el.style.opacity = 1.0;
        el.style.filter = 'alpha(opacity=10)';
    }

/*onmouseout*/
function dimCurrent(el) {
        el.style.opacity = 0.5;
        el.style.filter = 'alpha(opacity=5)';

    }

Why so complicated? 为什么这么复杂? From what I see, CSS is enough for this: 从我看来,CSS就足够了:

<ul>
    <li>A</li>
    <li>B</li>
    <li>C</li>
    <li>D</li>
    <li>E</li>
</ul>

ul:hover li {
  opacity: 0.5;
}

ul li:hover {
  opacity: 1;
}

http://jsfiddle.net/fkAyb/ http://jsfiddle.net/fkAyb/

You can change the opacity this way: 您可以通过以下方式更改不透明度:

document.getElementById('someid').style.opacity = '0.5';

Use onmouseover and onmouseout events for the rest. 其余使用onmouseover和onmouseout事件。

An idea I didn't try: 我没有尝试过的想法:

  1. Give each div an id, eg "div-1", "div-2" 给每个div指定一个ID,例如“ div-1”,“ div-2”
  2. Store all of them in an array. 将它们全部存储在一个数组中。
  3. Listen to onmouseover event, loop the array and change the opacity of all the elements that are in the array that are different to the current Id. 侦听onmouseover事件,循环数组并更改数组中与当前ID不同的所有元素的不透明度。
  4. Listen to onmouseout event and revert all the opacity to 1. 监听onmouseout事件,并将所有不透明度恢复为1。

If it's not clear enough let me know. 如果不清楚,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM