【问题标题】:jQuery selective hoverjQuery 选择性悬停
【发布时间】:2010-04-12 20:58:26
【问题描述】:

我正在尝试用 jQuery 做一个简单的任务:我有一个单词列表,当悬停时,应该在其对应的图像中淡入淡出。例如:

<a href="#" class="yellow">Yellow</a>
<a href="#" class="blue">Blue</a>
<a href="#" class="green">Green</a>

<img src="yellow.jpg" class="yellow">
<img src="blue.jpg" class="blue">
<img src="green.jpg" class="green">

我目前对每个链接/图像都这样做:

$('a.yellow').hover(
  function () {
    $('img.yellow').fadeIn('fast');
    },
    function () {
     $('img.yellow').fadeOut('fast');
     });

上面的方法效果很好,但是我还在学习,我想有一个更好的方法可以做到这一点,而不是重复函数。

谁能在这里给我一些启示?如何改进此代码?

【问题讨论】:

    标签: jquery hover selection fadein


    【解决方案1】:
    <a href="#" class="yellow" data-type="color">Yellow</a>
    <a href="#" class="blue" data-type="color">Blue</a>
    <a href="#" class="green" data-type="color">Green</a>
    

    jQuery 代码

    $('a[data-type=color]').hover(
      function () {
        $('img.'+$(this).attr("class")).fadeIn('fast');
        },
        function () {
         $('img.'+$(this).attr("class")).fadeOut('fast');
         });
    });
    

    我认为你应该试试这个。我使用data- 作为自定义属性的前缀,因为它符合 html5。如果你愿意,你可以说data-something。

    通常您可能不需要使用 data-color 自定义属性,但我认为为了使其更通用,我使用了该属性。你也可以做这样的代码:

    <a href="#" class="yellow">Yellow</a>
    <a href="#" class="blue">Blue</a>
    <a href="#" class="green">Green</a>
    

    然后

    $('a').hover(
      function () {
        $('img.'+$(this).attr("class")).fadeIn('fast');
        },
        function () {
         $('img.'+$(this).attr("class")).fadeOut('fast');
         });
    });
    

    但是这样的话,你应该确保所有的链接都是图片相关的链接。

    【讨论】:

      【解决方案2】:
      <a href="#" id="yellow" class="colorLink">Yellow</a>
      <a href="#" id="blue" class="colorLink">Blue</a>
      <a href="#" id="green" class="colorLink">Green</a>
      
      <img src="yellow.jpg" class="yellow">
      <img src="blue.jpg" class="blue">
      <img src="green.jpg" class="green">
      
      $("a.colorLink").hover(
          function(){
              $("img."+this.id).fadeIn('fast');
          },
          function(){
              $("img."+this.id).fadeOut('fast');
          }
      );
      

      这将为与图像对应的每个链接设置一个唯一的 ID。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-09-21
        • 1970-01-01
        • 2013-09-20
        • 1970-01-01
        • 1970-01-01
        • 2013-05-31
        相关资源
        最近更新 更多