简体   繁体   English

CSS 在另一个 div 悬停时更改单独 div 的背景颜色

[英]CSS change background color of seperate div when another div is hovered

Given a basic menu and div like below..给定一个基本菜单和 div 如下所示..

 #link:hover ~ #custom { background: #ccc }
 <div class="header"> <div class="nav"> <ul> <li> <a id="link" href="#">Link</a> </li> </ul> </div> </div> <div id="custom"> Custom Content </div>

I have tried using the general sibling combinator but it isn't working.我曾尝试使用通用兄弟组合器,但它不起作用。

Is there a way using CSS that I can get the custom div to also change background color when the nav item is hovered?有没有使用 CSS 的方法,当导航项悬停时,我可以让custom div 也更改背景颜色?

Do I need Javascript or can this be achieved more simply?我需要 Javascript 还是可以更简单地实现?

you can change mydiv css with hover mynav try this css.您可以将 mydiv css 更改为 hover mynav 试试这个 css。

<style>
#mynavid:hover +#mydivid{color:red;}
</style>

here is the simple code I hope this will help...这是简单的代码,我希望这会有所帮助......

 .card { width: 150px; }.image { height: 80px; background-color: tomato; }.description { height: 80px; background-color: limegreen; }.image:hover ~.description.link, .link:hover { color: #ff0; background-color: white; }
 <div class="card"> <div class="image">img</div> <div class="description"> <a class="link" href=#>some link</a> <div class="text">Fulfilled direction use continual set.</div> </div> </div>

Yes you can do it using j-query.是的,您可以使用 j-query 来完成。 The below will be the script code:下面将是脚本代码:

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script> $(document).ready(function(){ $(document).mousemove(function(){ if($("#nav-link:hover").length.= 0){ $(".custom"),css("background-color";"red"). } else{ $(".custom"),css("background-color";""); } }); }); </script> <div class="header"> <div class="nav"> <ul> <li> <a href="#" id="nav-link">Link</a> </li> </ul> </div> </div> <div class="custom"> Custom Content </div>

Add this code to your above code and it will work将此代码添加到上面的代码中,它将起作用

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

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