2 回答
TA贡献1875条经验 获得超3个赞
如果我没猜错,那很简单
$('document').ready(function() {
$('#backButton').on( "mouseover", function() {
$('#backButton > i').removeClass('fa-user-lock').addClass('fa-arrow-left');
});
$('#backButton').on( "mouseout", function() {
$('#backButton > i').removeClass('fa-arrow-left').addClass('fa-user-lock');
});
});
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" integrity="sha512-1PKOgIY59xJ8Co8+NE6FZ+LOAZKjy+KY8iq0G4B3CyeY6wYHN3yt9PW0XpSriVlkMXe40PTKnXrLnZ9+fkDaog==" crossorigin="anonymous" />
<a id="backButton" class="navbar-brand" href="/dashboard">
<i class="fas fa-user-lock"></i>
</a>
现在你的问题的第二部分 - 如何不硬编码类名?好吧,显然你需要做这样的事情——读取活动元素的类,记住它并在 mouseout 上使用……这样的事情……(我将backButtonID 更改为类以显示多个图标示例)
$('document').ready(function() {
// Remember active class
let tmpClass;
// On mouse over
$('.backButton').on( "mouseover", function() {
// get current class
tmpClass = $(this).children('i').attr('class').split(/\s+/);
// Swap
$(this).children('i').removeClass(tmpClass[1]).addClass('fa-arrow-left');
});
// On mouse out
$('.backButton').on( "mouseout", function() {
$(this).children('i').removeClass('fa-arrow-left').addClass(tmpClass[1]);
});
});
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" integrity="sha512-1PKOgIY59xJ8Co8+NE6FZ+LOAZKjy+KY8iq0G4B3CyeY6wYHN3yt9PW0XpSriVlkMXe40PTKnXrLnZ9+fkDaog==" crossorigin="anonymous" />
<a class="navbar-brand backButton" href="/dashboard">
<i class="fas fa-user-lock"></i>
</a>
<a class="navbar-brand backButton" href="/dashboard">
<i class="fas fa-bomb"></i>
</a>
<a class="navbar-brand backButton" href="/dashboard">
<i class="fas fa-bell-slash"></i>
</a>
TA贡献1712条经验 获得超3个赞
你可以试试这个,这样你就可以为具有相同功能的不同组件调用相同的函数。
function onBackButtonHover(e) {
var i = $(e).find('i.fas')
$(i).removeClass($(i).attr("default")).addClass($(i).attr("hover"))
}
function onBackButtonOut(e) {
var i = $(e).find('i.fas')
$(i).removeClass($(i).attr("hover")).addClass($(i).attr("default"))
}
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" integrity="sha512-1PKOgIY59xJ8Co8+NE6FZ+LOAZKjy+KY8iq0G4B3CyeY6wYHN3yt9PW0XpSriVlkMXe40PTKnXrLnZ9+fkDaog==" crossorigin="anonymous" />
<a id="backButton intranet" class="navbar-brand" href="/dashboard" onmouseover="onBackButtonHover(this)" onmouseout="onBackButtonOut(this)">
<i class="fas fa-user-lock" default="fa-user-lock" hover="fa-arrow-left"></i>
</a>
添加回答
举报