开发者

Need of optimized code for hide and show div in jQuery

开发者 https://www.devze.com 2022-12-28 19:03 出处:网络
I have a div: <div id=\"p1\" class=\"img-projects\" style=\"margin-left:0;\"> <a href=\"project1.php\"> <img src=\"image1.png\"/></a>

I have a div:

<div id="p1" class="img-projects" style="margin-left:0;">
  <a href="project1.php"> <img src="image1.png"/></a>
  <div id="p1" class="project-title">Bar Crawler</div>
</div>

On mouse-over I want to add an image with opacity and make the project-title shown. So I use this code:

<script type="text/javascript">
    $(function() {
        $('.project-title').hide();

            $('#p1.img-projects img').mouseover(
               function() {
                   $(this).stop().animate({ opacity: 0.3 }, 800);
                   $('#p1.project-title').fadeIn(500);
            });
            $('#p1.img-projects img').mouseout(
               function() {
                 开发者_StackOverflow中文版  $(this).stop().animate({ opacity: 1.0 }, 800);
                   $('#p1.project-title').fadeOut();
            });


            $('#p2.img-projects img').mouseover(
               function() {
                   $(this).stop().animate({ opacity: 0.3 }, 800);
                   $('#p2.project-title').fadeIn(500);
            });
            $('#p2.img-projects img').mouseout(
               function() {
                   $(this).stop().animate({ opacity: 1.0 }, 800);
                   $('#p2.project-title').fadeOut();
            });

    });

</script>

The code works fine but does anyone know a way to optimize my code?

Thank you


You can use one .hover() function for everything that's relative not ID dependent, like this:

$('.img-projects img').hover(function() {
   $(this).stop().animate({ opacity: 0.3 }, 800)
          .closest('.img-projects').find('.project-title').fadeIn(500);
}, function() {
   $(this).stop().animate({ opacity: 1.0 }, 800)
          .closest('.img-projects').find('.project-title').fadeOut();
});

This finds all elements relative to the one that was hovered instead of having a different function to handle each one...you could probably remove the IDs from your elements as well unless they serve another purpose. Since currently you have invalid HTML with the ID being used twice each time, this resolves that as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消