【问题标题】:confused with attr to use with mouseover() and mouseout()(image swap)与 attr 混淆以与 mouseover() 和 mouseout() 一起使用(图像交换)
【发布时间】:2014-12-02 15:48:12
【问题描述】:

我正在使用jQuery 在悬停时切换图像。这是我的代码。 HTML

<img class="commentImg" src="images/comments.png" data-swap="images/comment_hover.png" alt="">  

jQuery

$(".commentImg").hover(function() {
     var swap = $(this).attr("data-swap");
     $(this).attr('src', swap);
},
function() {
     var swap = $(this).attr("data-swap");
     $(this).removeAttr(swap);
 });  

mouseover 工作正常,但 mouseout 不行。你们能帮帮我吗?

【问题讨论】:

    标签: javascript jquery html css attr


    【解决方案1】:

    我找到了另一种解决方案,它可以完成任务,如果您有很多图像,它也很有用。这是代码。可能会帮助那里的人,

    HTML

      <div class="large-8 columns commentWrap">
         <img class="commentImg" src="images/comments.png" data-swap="images/comment_hover.png" alt="">
         <p class="inline_cmt">Comments (3)</p>
       </div>
       <div class="large-2 columns inline_rply">
         <img class="replyImg" src="images/reply.png" data-swap="images/reply_hover.png" alt="">
         <p class="dash_reply">Reply</p>
       </div>
       <div class="large-2 columns reportWrap">
          <img class="reportImg" src="images/report.png" data-swap="images/report_hover.png" alt="">
          <p class="inline_rep">Report</p>
       </div>
    

    jQuery

    var sourceSwap = function() {
      var $this = $(this);
      var newSource = $this.data('swap');
      $this.data('swap', $this.attr('src'));
      $this.attr('src', newSource);
      }
    
    $('.commentImg').hover(sourceSwap, sourceSwap);
    $('.replyImg').hover(sourceSwap, sourceSwap);
    $('.reportImg').hover(sourceSwap, sourceSwap);
    

    【讨论】:

      【解决方案2】:

      你需要存储它

      //store current src in a attribute
      $(".commentImg").attr('data-src', function() {
        return $(this).attr('src');
      })
      $(".commentImg").hover(function() {
        var swap = $(this).attr("data-swap");
        $(this).attr('src', swap);
      }, function() {
        var src = $(this).attr("data-src");
        $(this).attr('src', src);
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
      <img class="commentImg" src="//placehold.it/64/ff0000" data-swap="//placehold.it/64/ff00ff" />
      <img class="commentImg" src="//placehold.it/64/00ff00" data-swap="//placehold.it/64/ffff00" />
      <img class="commentImg" src="//placehold.it/64/0000ff" data-swap="//placehold.it/64/00ffff" />

      【讨论】:

        猜你喜欢
        • 2011-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-12
        • 1970-01-01
        • 1970-01-01
        • 2012-12-21
        相关资源
        最近更新 更多