[英]Change attribute of multiple elements on hover by using CSS
I have two div elements which are placed next to each other, i want to change the attribute background-color
of both of them if the user hovers over one of them. 我有两个div元素放在一起,如果用户将鼠标悬停在其中一个上,我想更改它们的属性
background-color
。
So the background-color should be initially set to #d8d8d8
for both divs and should change to #cacaca
on both divs if i hover over one of the divs. 因此,对于两个div,背景颜色最初应设置为
#d8d8d8
,如果我将鼠标悬停在其中一个div上, #cacaca
在两个div上更改为#cacaca
。
I solved it using jquery: 我用jquery解决了它:
$("#FOO").hover ( function() { $(this).css("background-color","#CACACA"); $("#BAR").css("background-color","#CACACA"); }, function() { $(this).css("background-color","#D8D8D8"); $("#BAR").css("background-color","#D8D8D8"); } ) $("#BAR").hover ( function() { $(this).css("background-color","#CACACA"); $("#FOO").css("background-color","#CACACA"); }, function() { $(this).css("background-color","#D8D8D8"); $("#FOO").css("background-color","#D8D8D8"); } )
.buttons { border:1px solid black; background-color: #D8D8D8; height: 100px; font-family: play; font-size: 30px; text-align:center; vertical-align: middle; line-height: 100px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> <div class="col-xs-10 buttons" id="FOO" style="border-right: 0px"> <span style="padding-left:100px">FOO</span> </div> <div class="col-xs-2 buttons" id="BAR" style="border-left: 0px"> <span>BAR</span> </div>
Is there a better way to achieve this? 有没有更好的方法来实现这一目标? Maybe only with css?
也许只有css?
You can wrap columns in div
and add :hover
on it: 你可以在
div
包装列并添加:hover
在它上面:
.buttons { border:1px solid black; background-color: #D8D8D8; height: 100px; font-family: play; font-size: 30px; text-align:center; vertical-align: middle; line-height: 100px; } .row:hover > .buttons { background-color: #CACACA; }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> <div class='row'> <div class="col-xs-10 buttons" id="FOO" style="border-right: 0px"> <span style="padding-left:100px">FOO</span> </div> <div class="col-xs-2 buttons" id="BAR" style="border-left: 0px"> <span>BAR</span> </div> </div>
I would give both divs the same css-class like so: 我会给两个div同样的css类,如下所示:
<div class="col-xs-10 buttons buttonset1" id="FOO" style="border-right: 0px">
<span style="padding-left:100px">FOO</span>
</div>
<div class="col-xs-2 buttons buttonset1" id="BAR" style="border-left: 0px">
<span>BAR</span>
</div>
Then in jquery you can make the following rule: 然后在jquery中,您可以制定以下规则:
$(".buttonset1").hover
(
function()
{
$(".buttonset1").css("background-color","#CACACA");
},
function()
{
$(".buttonset1").css("background-color","#D8D8D8");
}
)
You are more flexible this way. 你这样更灵活。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.