如果未隐藏DIV,如何切换图像

时间:2015-01-01 14:08:05

标签: javascript jquery html

如果按下DIV,我有以下JQuery显示菜单:

var pull = $('#mmTrigger');
menu = $('.ulMM');
menuHeight = menu.height();

$(pull).on('click', function(e) {
    e.preventDefault();
    menu.slideToggle();
});

HTML:

<div class="dvMain">
        <ul class="ulMM specClear">
            <li class="liMM"><a href="#" class="mmLink">Portfolio</a></li>
            <li class="liMM"><a href="#" class="mmLink">About</a></li>
            <li class="liMM"><a href="#" class="mmLink">Contact</a></li>
            <li class="liMM"><a href="#" class="mmLink">Forum</a></li>
        </ul>
        <div id="mmTrigger"><img src="nav-icon.png" class="imgMenu" /></div>
    </div>

我将脚本修改为:

    $(pull).on('click', function(e) {
     e.preventDefault();
     menu.slideToggle();
     if (menu.is(':hidden')) {
         $(".imgMenu").attr("src", "nav-icon.png");
     } else {
         $(".imgMenu").attr("src", "iconx.png");
     }
 });

但点击DIV后,X会停留,并且在菜单关闭后不会返回nav-icon.png

如何解决此问题,以便X更改菜单图标。

我添加了这句话:alert (menu.is(':hidden'));它总是返回false。

2 个答案:

答案 0 :(得分:2)

您应该在slideToggle动画停止后更改图标。您可以在callback中执行此操作:

$(pull).on('click', function (e) {
    e.preventDefault();
    menu.slideToggle(function () {
        // slideToggles callback
        if (menu.is(':hidden')) {
            $(".imgMenu").attr("src", "nav-icon.png");
        } else {
            $(".imgMenu").attr("src", "iconx.png");
        }
    });
});

答案 1 :(得分:2)

尝试在完成幻灯片切换时更改图片:请参阅此处:http://api.jquery.com/slidetoggle/

&#13;
&#13;
$(document).ready(function(){
	var pull = $('#mmTrigger');
	menu = $('.ulMM');
	menuHeight = menu.height();

	$(pull).on('click', function(e) {
	   e.preventDefault();
	     menu.slideToggle("slow", function() {
	     alert( ! menu.is(":visible") );
	    if (! menu.is(":visible")) {
	         $(".imgMenu").attr("src", "https://maps.google.com/mapfiles/kml/shapes/schools_maps.png");// icons added to show demo use your own icons.
	     } else {
	         $(".imgMenu").attr("src", "http://labs.google.com/ridefinder/images/mm_20_black.png");
	     }
	     });
	 });
	
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dvMain">
        <ul class="ulMM specClear">
            <li class="liMM"><a href="#" class="mmLink">Portfolio</a></li>
            <li class="liMM"><a href="#" class="mmLink">About</a></li>
            <li class="liMM"><a href="#" class="mmLink">Contact</a></li>
            <li class="liMM"><a href="#" class="mmLink">Forum</a></li>
        </ul>
        <div id="mmTrigger"><img src="https://maps.google.com/mapfiles/kml/shapes/schools_maps.png" class="imgMenu" /></div>
    </div>
&#13;
&#13;
&#13;