简体   繁体   中英

Javascript hide/show - more elegant way to do this?

I'm looking for a more elegant way to make a hide/show of divs using inline Javascript.

If you mouse over the orangish/yellow circle logos over the cars the tag should appear. When moused out they should disappear.

URL:

http://174.120.239.48/~peakperf/

<div class="second">
    <div id="speech2" style="display: none">
        <img src="<?php bloginfo('template_url'); ?>/images/speech2.png" width="334" height="50">
        </div>
    <a id="various2" href="#inline2,javascript:HideContent('speech1')" title="" onmouseover="HideContent('speech1'); return true;">
        <img src="<?php bloginfo('template_url'); ?>/images/clicker.png" width="62" height="50" onmouseover="document.getElementById('speech2').style.display = 'block'" onmouseout="document.getElementById('speech2').style.display = 'none'">
    </a>
</div>

Here's the pastebin of the code used:

http://pastebin.com/JsW6eJRZ

The more elegant solution is to utilize JQuery. Once you include the library into a file, a div show is done using the following selector

$('#idOfDiv').show();

Or if there are no ids but rather classes

$('.ClassName').show();

Now instead of having onclick events in the html as you have right now, you just bind them in jquery in the ready() method like so:

$(document).ready(function()
{
   $('#idOfDiv').bind('click', function()
   {
      //do work here in this anonymous callback function
   });
});

All of this can be done in a external js file so that will significantly clean up your html code and put all your javascript logic into one location.

EDIT: Example applied to your situation

$(document).ready(function() 
{
   $('#various1').mouseover(function()
   {
      $('#speech1').show();
   });

   $('#various1').mouseout(function()
   {
      $('#speech1').hide();
   });   
});

If you get crafty and utilize a for loop then you could just append the number to the end of the string that represents the selectors like so

$(document).ready(function() 
{
   for(var i = 1; i < 7; i++)
   {
      $('#various' + i).mouseover(function()
      {
         $('#speech' + i).show();
      });

      $('#various' + i).mouseout(function()
      {
         $('#speech' + i).hide();
      });   
   }
});

The mouseout and mouseover functions are just the explicit version of using like so

$('selector').bind('mouseover', function()
{
});

$('selector').bind('mouseout', function()
{
});

Have you looked into using jQuery for this? Also, why does the code need to be inlined?

I would recommend doing something like this: http://jsfiddle.net/4N9ym/2/

Note that I have things inverted here (you would probably want to animate in instead of animating out).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM