繁体   English   中英

当另一个元素处于活动状态时更改元素的样式

[英]Change Styles Of Element When Another Element Is Active

类2为焦点或悬停时,我可以更改类1的样式吗? CSS有什么办法吗?

像这儿。

<button class='class 1'></button>
<button class='class 2'></button>

您可以使用mouseovermouseout

 $('.class').on('mouseover', function(e) { $('.class').not($(this)).addClass('hover') }) $('.class').on('mouseout', function(e) { $('.hover').removeClass('hover') }) 
 .hover { background: green; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class='class 1'>Test</button> <button class='class 2'>Test 1</button> 

尝试这个。 将鼠标悬停在按钮2上时,它将更改按钮1的背景色

 $(document).ready(function() { $('.class2').hover(function() { $('.class1').css('background-color', 'blue')}, function(){ $('.class1').css('background-color', '') }) }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class='class1'>Button</button> <button class='class2'>Button</button> 

您可以尝试使用jQuery的.hover()

请注意:类名不允许在其中留空格。

 $('.class2').hover( function() { $('.class1').css({color:'red'}); }, function() { $('.class1').css({color:'blue'}); } ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class='class1'>Button 1</button> <button class='class2'>Button 2</button> 

仅使用CSS可以做到这一点,但可能有点挑剔。

您可以使用伪类 focushover并选择类.class1紧随其后的元素。 因为+在您可以使用flexorder来移动按钮之后立即将其定位为元素,所以它们以正确的顺序出现:

 .class2:hover+.class1 { background: lime; color: red; } .class2:focus+.class1 { background: red; color: white; } .wrapper { display: flex; } .class1 { order: 1; } .class2 { order: 2; } 
 <div class="wrapper"> <button class='class2'>Button2</button> <button class='class1'>Button1</button> </div> 

尝试这个

html

    <button class='class1'>button1</button>
    <button class='class2'>button2</button>

的CSS

    .class1:hover + .class2,
    .class1:active + .class2,
    .class1:focus + .class2{
          background: blue;
     }

    .class2:hover + .class1,
    .class2:active + .class1,
    .class2:focus + .class1{
          background: green;
     }

谢谢。

暂无
暂无

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

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