最後發現一些代碼會改變DOM中hover元素之上svg的懸停顏色,但現在我想向它添加一些邏輯。你可以在.on()函數中放入一個if/else語句嗎?
HTML
<div class="tag--active grid__item small--one-third medium--one-third large--one-third xlarge--one-third">
<div class="tag-container">
<a class="svg-filter-link" href="">
<div class="top clearfix">
<!--?xml version="1.0" encoding="UTF-8" standalone="no"?-->
<svg width="41px" height="48px" viewBox="0 0 41 48" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 39.1 (31720) - http://www.bohemiancoding.com/sketch -->
<title>filter-icn-bedbug</title>
<desc>Created with Sketch.</desc>
<defs></defs>
<g id="Pest-Peeve-Web" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="Shopfront" transform="translate(-402.000000, -706.000000)" fill="#C8C8C8">
<g id="filter-icn-pest" transform="translate(154.000000, 698.000000)">
<path d="M284.00492,...bunch of numbers... L277.822737,10.9244995 Z" id="filter-icn-bedbug"></path>
</g>
</g>
</g>
</svg>
</div>
</a>
<div class="bottom">
<a title="Title" href="/collections/tag">Link Text</a>
</div>
</div>
</div>
的JavaScript
$(document).on({
mouseenter: function() {
$(this).closest('.tag-container').find('svg path').css({'fill': '#0BACFF'});
},
mouseleave: function() {
$(this).closest('.tag-container').find('svg path').css({'fill': '#939393'});
}
}, ".tag-container a");
在這一點上,SVG會改變顏色像它應該徘徊的時候,再變回不徘徊的時候。然而,問題在於,當頁面加載時,「標記 - 活動」圖標(活動鏈接)已被高亮顯示,因此在將鼠標懸停在其上方後,它將刪除突出顯示。
我想補充的邏輯說,「如果它已經是這個顏色,什麼也不做」,但下面的不會起作用:
$(document).on({
if ($(this).closest(".grid__item").hasClass("tag--active") == 'false') {
mouseenter: function() {
$(this).closest('.tag-container').find('svg path').css({'fill': '#0BACFF'});
},
mouseleave: function() {
$(this).closest('.tag-container').find('svg path').css({'fill': '#939393'});
}
}
}, ".tag-container a");
我想我必須使用錯誤的語法。你會怎麼做?
我會檢查你從'$(this)'得到的上下文。嘗試將其輸出到'console.log()' – bbodien
您正在傳遞'on'對象,其中有兩個屬性表示事件及其處理程序。他們是兩個單獨的事件,所以'if'需要在每個方法內執行。你不能在對象文字中有'if'語句,'while/for'循環和其他類似的東西,這會導致語法錯誤。 – ste2425
啊,謝謝澄清。我現在有了更好的理解。 – Kevmon