javascript - Combining addClass with fadeIn on mouseenter
问题描述
So, I have written JavaScript code that uses the JQuery library to swap classes on hover.
$("#workBG").on({
mouseenter : function() {
$("#workplay").addClass("workBG", 200);
$("#workplay").removeClass("diagR", 200);
}
,
mouseleave : function() {
$("#workplay").addClass("diagR", 200);
$("#workplay").removeClass("workBG", 200);
}
})
This code works but I would like to have the class fadeIn and fadeOut considering that it swaps background images but it does so harshly without the fadeIn and fadeOut. I have seen similar questions but they were all from five or six years ago and I would like to know if there is any better way to do this now.
From one of the older questions, I saw that they had answered with
.addClass("workBG", 200);
where the 200 is the time for the class to fadeIn. As far as I can tell, this does not work now or I am doing something wrong. I did check the JQuery documentation and there was nothing about this under the addClass API documentation.
In Addition:
HTML code:
<div id="workplay" class ="row text-center mt-5 diagR">
<div class ="col-sm-6 align-self-center changework">
<p id= "workBG" class ="display-1 font-weight-bold text-warning">WORK.</p>
</div>
<div class ="col-sm-6 align-self-center">
<p id= "playBG" class ="display-1 font-weight-bold">PLAY.</p>
</div>
</div>
This is the html code that is related to the JS and the backgrounds are applied through the classes.
解决方案
just add transition property on your element don't use 2nd parameter with addClass / removeClass function
$("#workBG").on({
mouseenter: function() {
$("#workplay").addClass("workBG");
$("#workplay").removeClass("diagR");
},
mouseleave: function() {
$("#workplay").addClass("diagR");
$("#workplay").removeClass("workBG");
}
})
#workplay {
transition: 2s;
}
.workBG {
background: red;
}
.diagR {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="workBG">
<div id="workplay">asdasdasd</div>
</div>
推荐阅读
- r - 无法在 R 中启动 H2O:h2o.init() 中的错误 H2O 无法启动,停止执行
- apache - 无法在 nginx 上用 .html 名称重命名特定的 .php 文件
- r - 如何让“msa”包与所有字符一起使用
- javascript - 如何使用 Babel 转译 JavaScript?
- java - 将 java 函数/方法转换为 json 对象
- android - Android FirebaseAuth getCurrentUser() 在全新安装/构建后返回用户
- vba - 在不触发更改侦听器的情况下更改滚动条的值
- angular - 更改路线始终显示主要组件,我如何将其隐藏/从特定路线的视图中删除?
- php - TYPO3 9.5.x:从版本 6 LTS 升级到 7 LTS 到 9.5.3 后,每次页面树都崩溃
- xamarin - 为什么 CrossCurrentActivity.Current.Activity 总是为 Xamarin.Forms 中的任何其他页面提供 MainActivity?