当& lt; li>改变我们的Div类

When <li> get Hover Change the out Div Class

本文关键字:Div 我们 lt li 改变      更新时间:2023-09-26

因此,当有人悬停<li>时,我需要我的div得到他的类更改。

我该怎么做?

这是可能的只用css还是我需要把一些JS里面?

编辑1:每个li将有一个特定的id,div将接收id作为一个类。

我认为你应该使用JQuery:

$(document).ready(function(){
$("li").mouseover(function(event){
   $("#capa").addClass("class");
});
});

要根据悬停子<li>的ID为父<div>元素分配类,首先检查悬停并获得ID名称,然后将其分配给父<div>

下面是一个代码,你将能够在一个页面上使用几个div,它将重置类名离开<li>悬停,通过使用jQuery方法的out处理程序:

$(".changeme ul li").hover(function(){
    $(this).parents("div").addClass($(this).attr("id"));
}, function(){
    $(this).parents("div").removeClass($(this).attr("id"));
});
.changeme{
    background-color:#eee;
}
.changeme.firstli{
    background-color:#ffd;
}
.changeme.secondli{
    background-color:#fdd;
}
.changeme.thirdli{
    background-color:#dfd;
}
.changeme.fourthli{
    background-color:#ddf;
}
.changeme.fifthli{
    background-color:#ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="unaffected">
    <p> some other parenting div, not affected</p>
    <div class="changeme">
    <p>some text, nothing changes</p>
    <ul>
        <li id="firstli">we are changing our parentting div!</li>
        <li id="secondli">we are changing our parentting div!</li>
        <li id="thirdli">we are changing our parentting div!</li>
    </ul>
    <p>some text, nothing changes</p>
    <ul>
        <li id="fourthli">we are changing our parentting div!</li>
        <li id="fifthli">we are changing our parentting div!</li>
    </ul>
    <p>some text, nothing changes</p>
</div>
</div>

https://jsfiddle.net/svArtist/adq5dr68/

进入div样式的类定义,并在名称附近添加"li:hover";

 .yourDiv { font-size:14pt; }

然后转到这个

 .yourDiv li:hover { font-size:14pt; }

你可以只使用:hover属性,这样你就不必改变div的类,这只能用javascript来做。

CSS悬停属性可以用来指定元素在悬停时的显示方式,但不能指定其他元素在第一个元素悬停时的显示方式。实现这种复杂的行为需要一点JavaScript。

(function() {
  var div = document.getElementById("parent"); // save a reference to the target div
  var lis = div.querySelectorAll("li"); // get your <li> tags
  for (var i = 0, len = lis.length; i < len; i++) {
    lis[i].onmouseover = updateDivClass; // attach the event listener to each tag
  }
  div.onmouseout = function() { // remove class when no longer hovering over div
    this.className = "";
  };
  function updateDivClass() { // apply class to div when hovering over <li> tag
    div.className = this.id;
  }
})();
.Class1 {
  background-color: #df7000;
  font-family: Calibri;
  color: black;
}
.Class2 {
  background-color: purple;
  color: white;
  font-family: Segoe UI;
}
.Class3 {
  background-color: black;
  color: lightgreen;
  font-family: courier;
}
<div id="parent">
  Hover over a class below to apply the class to the entire div.
  <ul>
    <li id="Class1">Black Calibri with Orange Background</li>
    <li id="Class2">White Segoe UI with Purple Background</li>
    <li id="Class3">Light Green Courier with Black Background</li>
  </ul>
</div>