[英]Trigger a hover effect while hovering on another div
At the moment, I am learning how to write in javascript and jquery.I wrote a simple jquery code where when you hover one div, a second div will be hovered too. 目前,我正在学习如何用javascript和jquery编写代码。我编写了一个简单的jquery代码,当您将鼠标悬停在一个div时,第二个div也将被悬停。 However, the code I wrote is not working.
但是,我编写的代码无法正常工作。 My knowledge is not enough to fix the mistake I made by myself that's why if someone can help me I am going to be really grateful.
我的知识不足以纠正我自己犯的错误,这就是为什么如果有人可以帮助我,我将非常感激。
PS: I know that it can be done only with CSS but I am not interested in that. PS:我知道只能用CSS做到这一点,但我对此并不感兴趣。
My code: 我的代码:
$('.Box1').mouseover(function(e) { $('.Box2').trigger(e.type); })
body{ margin:0; padding:0; background-color:green; } .Box1{ position:relative; width:100vw; height:10vh; transition: background-color 1s ease; } .Box1:hover{ background-color:#FFF; } .Box2{ position:absolute; top:10vh; width:100vw; height:20vw; background-color:red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="Box1"></div> <div class="Box2"></div>
You'll just have to "fake" a hover event. 您只需要“伪造”悬停事件即可。 Take any code that you would have attached to the .Box2:hover css and assign it to a class.
接受将附加到.Box2:hover css的任何代码,并将其分配给一个类。 When you hover over .Box1, add the class to .Box2, when you hover off, remove the class.
当您将鼠标悬停在.Box1上时,将该类添加到.Box2中,当您将鼠标悬停在该框上时,请删除该类。 The code would look like the following:
该代码如下所示:
.Box2{
position:absolute;
top:10vh;
width:100vw;
height:20vw;
background-color:red;
transition: background-color 1s ease;
}
.Box2:hover, .Box2.hovered {
background-color: #FFF;
}
$(function () {
$('.Box1').mouseover(function(e) {
$('.Box2').addClass("hovered");
});
$(".Box1").mouseout(function () {
$(".Box2").removeClass("hovered");
});
// or optionally using .hover() for in/out handling as per A. Wolff's comment
$(".Box1").hover(function () {
$(".Box2").addClass("hovered");
}, function () {
$(".Box2").removeClass("hovered");
});
});
Your code does trigger the mouseover event for Box2 - you can test this by adding a handler: 您的代码确实触发了Box2的mouseover事件-您可以通过添加处理程序进行测试:
$('.Box2').mouseover(function() {console.log('hello')})
However, this does not activate the css :hover property of Box2 (if it were defined). 但是,这不会激活Box2的css:hover属性(如果已定义)。 You will probably need to write a handler for Box2's mouseover event that manipulates the css properties.
您可能需要为Box2的mouseover事件编写一个处理程序,以处理css属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.