我想實現jquery hover()並且我的代碼運行良好。爲了使用jqueury hover()運行addClass()和removeClass(),我必須定義如下面代碼所示的選擇器。但是它的浪費會導致兩次聲明選擇器,我怎麼能簡化這個冗餘代碼來聲明選擇器一次。如何簡化Redudant代碼jquery hover()
$('.main ul li a, .content-wrap .content').hover(
function() {
//start redudant code
var mainAnchor = $(this).data('hover');
var mainData = $('.main li a[data-hover= ' + mainAnchor + ']');
var contentData = $('.content-wrap .content[data-hover= ' + mainAnchor + ']');
//end redudant code
mainData.addClass('active');
contentData.addClass('active');
contentData.siblings().addClass('hidden');
$(this).addClass('active');
},
function() {
//start redudant code
var mainAnchor = $(this).data('hover');
var mainData = $('.main li a[data-hover= ' + mainAnchor + ']');
var contentData = $('.content-wrap .content[data-hover= ' + mainAnchor + ']');
//end redudant code
mainData.removeClass('active');
contentData.removeClass('active');
contentData.siblings().removeClass('hidden');
$(this).removeClass('active');
});
.content-wrap {
margin-top: 30px;
padding-bottom: 60px;
background-color: yellow;
clear: both;
overflow: hidden;
/*position: relative;*/
}
.content {
padding: 80px;
float: left;
margin-right: 10px;
cursor: pointer;
transition: 0.2s ease-in;
position: relative;
}
.tool-tip {
position: absolute;
bottom: -20px;
left: 0;
background-color: white;
opacity: 0;
transition: 0.1s ease-in;
}
.content.active .tool-tip {
opacity: 1;
}
.main li a.active {
background-color: red;
color: white;
}
.content.active {
border: 2px solid red;
}
.hidden {
opacity: 0.7;
}
.content.hidden {
background-color: gray;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
.blue {
background-color: blue;
}
.purple {
background-color: purple;
}
.brown {
background-color: brown;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
<ul>
<li><a href="" data-hover="item1">item 1</a></li>
<li><a href="" data-hover="item2">item 2</a></li>
<li><a href="" data-hover="item3">item 3</a></li>
<li><a href="" data-hover="item4">item 4</a></li>
<li><a href="" data-hover="item5">item 5</a></li>
</ul>
</div>
<div class="content-wrap">
<div class="content red" data-hover="item1">
<p>content 1</p>
<div class="tool-tip">
content 1 is active
</div>
</div>
<div class="content green" data-hover="item2">
<p>content 2</p>
<div class="tool-tip">
content 2 is active
</div>
</div>
<div class="content blue" data-hover="item3">
<p>content 3</p>
<div class="tool-tip">
content 3 is active
</div>
</div>
<div class="content purple" data-hover="item4">
<p>content 4</p>
<div class="tool-tip">
content 4 is active
</div>
</div>
<div class="content brown" data-hover="item5">
<p>content 5</p>
<div class="tool-tip">
content 5 is active
</div>
</div>
</div>
它看起來比我簡單,但我沒有注意到toggleClass()可以在mouseout時觸發。感謝您的建議 – rnDesto
但我想知道爲什麼當我懸停對象時,它不能讓課程激活。當我檢查我的瀏覽器中的檢查元素時,它沒有添加活動的類 – rnDesto
它在那裏開始也許因此被刪除,而不是?你也可以使用'e.type ==''mouseout''來創建一個布爾標誌來傳遞給toggleClass來強制它的添加/刪除,這取決於布爾型 – charlietfl