[英]Toggling opacity of divs when clicking on another div
I'm trying to make a div toggle the opacity of multiple other divs on click. 我正在尝试使一个div在单击时切换多个其他div的不透明度。 If anyone could point me in the right direction as to where I'm going wrong here, that would be great :)
如果有人能指出我在哪里出问题的正确方向,那将是很好的:)
function toggle_opacity(className) {
var x = document.getElementsByClassName(className);
if(x.style.opacity == '0')
x.style.opacity = '1';
else
x.style.opacity = '0';
}
getElementsByClassName
will return an array, so wrap your code in a loop: getElementsByClassName
将返回一个数组,因此将代码包装在循环中:
function toggle_opacity(className) {
var x = document.getElementsByClassName(className);
for(i = 0; i < x.length; i++){
if(x[i].style.opacity == '0')
x[i].style.opacity = '1';
else
x[i].style.opacity = '0';
}
}
Your JSFiddle has 3 problems. 您的JSFiddle有3个问题。
1) document.getElementsByClassName(className)
returns an array, so you need to select the first element: 1)
document.getElementsByClassName(className)
返回一个数组,因此您需要选择第一个元素:
var x = document.getElementsByClassName(className)[0];
2) Your if
needs to check if the opacity is 0
, not '0'
. 2)您
if
需要检查不透明度是否为0
而不是'0'
。
3) Your JS needs to be in <head>
, not onLoad
. 3)您的JS必须位于
<head>
,而不是onLoad
。
Here's an updated JSFiddle . 这是更新的JSFiddle 。
may be you want this I done with jquery 也许你想要我用jQuery完成
html-- html--
<div id="div_1" class="ope">
</div>
<div id="div_2" class="ope">
</div>
<div id="div_3" class="ope">
</div>
css--- CSS ---
.ope{
width:200px;
height:100px;
background-color:pink;
margin-bottom:4px;
cursor:pointer;
}
jquery-- jQuery-
$(document).ready(function(){
$(".ope").click(function(){
var thisdiv = $(this).attr('id');
//alert(thisdiv);
$(".ope").css('opacity','1');
$("#"+thisdiv).css('opacity','0.5');
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.