【发布时间】:2014-10-23 22:06:34
【问题描述】:
我不得不在 WordPress 网站上的导航菜单元素上制作鼠标悬停动画效果。我已经设法使用以下代码完成了这项工作:
<!-- Marius was here :) -->
<style type="text/css">
.fancy-img {
height: 51px;
background-image: url(http://www.minortest2.dk/wp-content/themes/bizway-childtheme/images/knap.png);
background-repeat: no-repeat;
}
.fancy-container {
padding-top: 10px;
}
.fancy {
position: absolute !important;
top: 0px;
z-index: -1;
overflow: hidden;
}
.container_24 .grid_sub_19 {
width: 83% !important;
}
</style>
<script type="text/javascript">
jQuery('#menu-topmenu').append('<li class="fancy"><div class="fancy-container"><div class="fancy-img"></div></div></li>');
jQuery('.menu-item-11').hover(function() {
jQuery('.fancy').stop();
jQuery('.fancy').css('width','107px');
jQuery('.fancy-img').css('background-size','107px 33px');
jQuery('.fancy').animate({ "left": "0px" }, 'fast' );
jQuery(this).children().css('color','#1c82e0');
jQuery(this).siblings().children().css('color','#fff');
})
jQuery('.menu-item-20').hover(function() {
jQuery('.fancy').stop();
jQuery('.fancy').css('width','141px');
jQuery('.fancy-img').css('background-size','141px 33px');
jQuery('.fancy').animate({ "left": "107px" }, 'fast' );
jQuery(this).children().css('color','#1c82e0');
jQuery(this).siblings().children().css('color','#fff');
})
jQuery('.menu-item-36').hover(function() {
jQuery('.fancy').stop();
jQuery('.fancy').css('width','155px');
jQuery('.fancy-img').css('background-size','155px 33px');
jQuery('.fancy').animate({ "left": "248px" }, 'fast' );
jQuery(this).children().css('color','#1c82e0');
jQuery(this).siblings().children().css('color','#fff');
})
jQuery('.menu-item-37').hover(function() {
jQuery('.fancy').stop();
jQuery('.fancy').css('width','107px');
jQuery('.fancy-img').css('background-size','107px 33px');
jQuery('.fancy').animate({ "left": "403px" }, 'fast' );
jQuery(this).children().css('color','#1c82e0');
jQuery(this).siblings().children().css('color','#fff');
})
jQuery('.menu-item-38').hover(function() {
jQuery('.fancy').stop();
jQuery('.fancy').css('width','111px');
jQuery('.fancy-img').css('background-size','111px 33px');
jQuery('.fancy').animate({ "left": "514px" }, 'fast' );
jQuery(this).children().css('color','#1c82e0');
jQuery(this).siblings().children().css('color','#fff');
})
</script>
<!-- Until here :D -->
结果可见here。尽管一切都像我预期的那样工作,但我对代码并不满意。如上所示,定位值是手动设置的。如果将新元素添加到菜单中,这可能会产生问题。我也有一些我想摆脱的重复代码。菜单项具有常见的类,例如 menu-item、menu-item-type-post_type、menu-item-object-page 等 WordPress 网站。优化我的代码的最佳方法是什么?任何指导或帮助都非常受欢迎。我很抱歉我的最佳实践代码不是那么好,但我仍在学习一些基础知识。 :)
【问题讨论】:
-
你只需要一个选择器:
jQuery('[class^="menu-item-"]') -
从@mevius 获取选择器并为不同的css样式编写一个函数
标签: javascript jquery html css wordpress