【问题标题】:Javascript hide/show - more elegant way to do this?Javascript 隐藏/显示 - 更优雅的方式来做到这一点?
【发布时间】:2011-07-10 17:21:47
【问题描述】:

我正在寻找一种更优雅的方式来使用内联 Javascript 隐藏/显示 div。

如果您将鼠标悬停在汽车上方的橙色/黄色圆圈徽标上,则应显示该标签。当鼠标移出时,它们应该会消失。

网址:

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>

这是所用代码的粘贴箱:

http://pastebin.com/JsW6eJRZ

【问题讨论】:

  • "使用内联 javascript" 使用内联 javascript 做任何事情都没有优雅的方法
  • 我完全同意。代码被继承。

标签: javascript dom-events unobtrusive-javascript


【解决方案1】:

更优雅的解决方案是使用 JQuery。 将库包含到文件中后,将使用以下选择器完成 div 显示

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

或者如果没有 id 而是类

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

现在不再像现在那样在 html 中添加 onclick 事件,您只需将它们绑定到 jquery 中的 ready() 方法中,如下所示:

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

所有这些都可以在外部 js 文件中完成,这样可以显着清理您的 html 代码 并将所有的 JavaScript 逻辑放在一个位置。

编辑: 适用于您的情况的示例

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

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

如果你很狡猾并使用 for 循环,那么你可以将数字附加到代表选择器的字符串末尾,就像这样

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

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

mouseout 和 mouseover 函数只是这样使用的显式版本

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

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

【讨论】:

  • @Raynos $(function() {}) $(document).ready(function(){}) 的简写?
  • 谢谢你,马修!我有6个这样的坏男孩。我将如何为其中 6 人做这件事?
  • 考克斯先生像个魅力人一样工作!你太棒了!
【解决方案2】:

您是否考虑过为此使用 jQuery?还有,为什么要内联代码?

我建议你这样做:http://jsfiddle.net/4N9ym/2/

请注意,我这里的东西是倒置的(你可能想要动画而不是动画)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多