[英]how to change the color of multiple div with onclick
假设我在页面中有3个跨度。 点击它们我正在展示一些东西。 现在我想改变我选择的div的颜色。
<div class="step_wrapper">
<div id="step_box1"> <span>Content of page 1</span>
</div>
<div id="step_box2"> <span>Content of page 2</span>
</div>
<div id="step_box2"> <span>Content of page 3</span>
</div>
</div>
我试图这样做
$("step_box1").toggle(function() {
$(this).css("background-color", "red");
},
function() {
$(this).css("background-color", "");
});
for 2nd div
$("step_box2").toggle(function() {
$(this).css("background-color", "red");
},
function() {
$(this).css("background-color", "");
});
而对于第三个
$("step_box2").toggle(function() {
$(this).css("background-color", "red");
},
function() {
$(this).css("background-color", "");
});
但我需要的是一次选择一个,选择哪一个div改变颜色,其他人恢复正常
在设置一个“红色”之前,您必须将所有颜色设置为正常颜色,如下所示:
$('.step_wrapper>div').css("background-color", "")
$(this).css("background-color", "red")
首先,给出你正在使用的toggle()
方法的签名我假设你已经包含了一个非常旧版本的jQuery(<1.9),因为该模式现已被弃用。 您应该将jQuery升级到项目中的较新版本。
其次,您可以通过在所有div元素上放置一个公共事件处理程序来实现此目的,如下所示:
<div class="step_wrapper">
<div id="step_box1">
<span>Content of page 1</span>
</div>
<div id="step_box2">
<span>Content of page 2</span>
</div>
<div id="step_box3">
<span>Content of page 3</span>
</div>
</div>
$(".step_wrapper div").click(function() {
$(this).addClass('active').siblings().removeClass('active');
});
注意使用addClass()
/ removeClass()
; 最好将样式放在外部样式表中并修改元素上的类名,而不是直接更改其内联样式。
您所要做的就是更改所选step_box
的背景颜色,并使其他的透明背景:
<div class="step_wrapper"> <div id="step_box1"> <span>Content of page 1</span> </div> <div id="step_box2"> <span>Content of page 2</span> </div> <div id="step_box2"> <span>Content of page 3</span> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> $('.step_wrapper > div').click(function() { $this = $(this); $this.css('background-color', 'red'); $this.siblings().css('background-color', 'transparent'); }) </script>
<head>
<title>sample Page</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<style>
.red {
background-color:red;
}
</style>
<script>
$(document).ready(function () {
$('.step_wrapper div').click(function () {
$('.step_wrapper div.red').removeClass('red')
$(this).addClass('red');
});
});
</script>
</head>
<body>
<div class="step_wrapper">
<div id="step_box1"> <span>Content of page 1</span>
</div>
<div id="step_box2"> <span>Content of page 2</span>
</div>
<div id="Div1"> <span>Content of page 3</span>
</div>
</div>
</body>
</html>
简单的CSS解决方案
这可以通过几行CSS完成。 请注意,必须将tabindex属性添加到每个DIV以允许它获得焦点。 此解决方案不需要任何JavaScript或库。
运行下面的代码段并单击文本行以查看其是否有效。
div:not(:focus) { background-color: none; color: black;} div:focus { background-color: red; color: white;}
<div> <div tabindex=1> <span>Content of page 1</span></div> <div tabindex=2> <span>Content of page 2</span></div> <div tabindex=3> <span>Content of page 3</span></div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.