最后发现一些代码会改变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