在div之后的悬停按钮上更改div css属性

时间:2017-10-04 07:53:56

标签: html css css3

  

将鼠标悬停在按钮上,但div不会更改其属性

通过将鼠标悬停在

之后创建的另一个标记(按钮)上来更改div的CSS属性



.zz {
  text-align: center;
  line-height: 100px;
  font-size: 20px;
  font-weight: bold;
  width: 100px;
  height: 100px;
  color: white;
  background: red;
  border: 4px solid black;
  margin: 100px;
  -webkit-transition: transform 1s;
  -webkit-transition-timing: ease-in-out;
  -webkit-transition-delay: 0.1s;
  float: left;
}

#btn:hover~.zz {
  background: green;
  -webkit-transform: rotate(40deg) translate(100px, 20px);
}

<div class="zz"> this is div</div>
<button id="btn"> hover me </button>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:5)

您需要将div放在DOM中用于兄弟选择器的按钮之后。或者,您可以使用javascript将类添加到.zz div。

.zz {
  text-align: center;
  line-height: 100px;
  font-size: 20px;
  font-weight: bold;
  width: 100px;
  height: 100px;
  color: white;
  background: red;
  border: 4px solid black;
  margin: 100px;
  -webkit-transition: transform 1s;
  -webkit-transition-timing: ease-in-out;
  -webkit-transition-delay: 0.1s;
  float: left;
}

#btn:hover ~ .zz {
  background: green;
  -webkit-transform: rotate(40deg) translate(100px, 20px);
}
<button id="btn"> hover me </button>
<div class="zz"> this is div</div>

答案 1 :(得分:1)

悬停元素需要放在按钮之后。

您也可以尝试使用 + 选择器:

&#13;
&#13;
.zz {
  text-align: center;
  line-height: 100px;
  font-size: 20px;
  font-weight: bold;
  width: 100px;
  height: 100px;
  color: white;
  background: red;
  border: 4px solid black;
  margin: 100px;
  -webkit-transition: transform 1s;
  -webkit-transition-timing: ease-in-out;
  -webkit-transition-delay: 0.1s;
  float: left;
}

#btn:hover + .zz {
  background: green;
  -webkit-transform: rotate(40deg) translate(100px, 20px);
}
&#13;
<button id="btn"> hover me </button>
<div class="zz"> this is div</div>
&#13;
&#13;
&#13;

您可以在此处了解详情:https://www.w3schools.com/cssref/css_selectors.asp

答案 2 :(得分:0)

#btn:hover~ .zz,当.zz悬停时,选择#btn个ID前面的每个#btn类,但在您的情况下#btn.zz的{​​{1}},因此未选择.zz

所以,只需改变:

<div class="zz"> this is div</div>    ---
<button id="btn"> hover me </button>     |
                            Here   <-----

<button id="btn"> hover me </button>
<div class="zz"> this is div</div>

&#13;
&#13;
.zz{ text-align:center; 
  line-height:100px; 
  font-size:20px; 
  font-weight:bold; 
  width:100px; height:100px; 
  color:white; 
  background:red; 
  border:4px solid black;
   margin:100px;
   
-webkit-transition: transform 1s ;
-webkit-transition-timing:ease-in-out;
 -webkit-transition-delay:0.1s;
  float:left;
    }
    
    #btn:hover ~.zz{ background:green;
                -webkit-transform:rotate(40deg) translate(100px,20px);
                
                
            }
&#13;
<button id="btn"> hover me </button>
<div class="zz"> this is div</div>
&#13;
&#13;
&#13;