繁体   English   中英

如何使用ID获取定位标记的背景图片网址

[英]How to get the background image url of anchor tag using id

我想将悬停效果添加到单个页面上的多个图像上。

每个图像都有单独的悬停图像,因此我正在使用动态背景图像更改。

我的逻辑是:

  1. 使用2个锚标记并隐藏1个
  2. 隐藏的图像包含应该在悬停图像上显示的图像。
  3. 当用户悬停时,应将第一个锚标记的背景图像替换为隐藏的锚标记的bg图像。

这是我的代码:

    <td class="cell-style-img">
    <a href="<?php echo $linkedin; ?>" id="img<?php echo '-'.$founder_count;?>" class="img-circular img_hover" style="background-image: url(<?php echo $src;?>);"/>
    <a href="<?php echo $linkedin; ?>" class="img-circular" style="display:none;background-image: url(<?php echo $hover_src;?>);" id="hover<?php echo '-'.$founder_count;?>"/>

    </a>
    </td>
$("a.img_hover").bind({

    mouseenter: function () {
      var id = $(this).attr('id');
      var id1 = id.replace (/[^\d.]/g, ''); 
      id1 = 'hover-'+(id1);
      //alert(id1);
      var bg = $("#"+id1).css('background-image').replace(/^url|[\(\)]/g, '');

      bg = bg.replace('url(','').replace(')','');
    $("#"+id).css('background-image', bg );
    },
    mouseout: function () {
      var id = $(this).attr('id');
      var id1 = id.replace (/[^\d.]/g, ''); 
      id1 = 'hover-'+(id1);
             $("#"+id).show();
             $("#"+id).show();
    }
});

我的问题是我无法获得第二个隐藏的锚标签的bg图像。

我如何使用jquery获取定位标记的背景图像。

代替使用多个元素,而使用data-*属性。

HTML:

<a href="#" data-hover="url('image2.jpg')" style="background-image: url('image1.jpg');">&nbsp;</a>

jQuery的:

$('a').hover( function() {
    var hoverImg = $(this).data('hover');
    var basicImg = $(this).css('background-image');
    $(this).data('hover', basicImg ).css('background-image', hoverImg );
});

DEMO




也许我在看它很容易,但是为什么不使用CSS(因为您已经在图像上使用了ID):

 
 
 
  
  a#imgId { background-image: url('image1.jpg'); } a#imgId:hover { background-image: url('image2.jpg'); }
 
  

DEMO

对于这种简单的问题,我认为这种方法太复杂了。 尝试一些更简单的事情,例如让CSS做繁重的工作。

这显然不适合您的现成情况(因为我无法确切地看到您在做什么),但是它应该引导正确的(或至少更容易的)路径。

演示: http //jsfiddle.net/u93efzb5/

HTML

<a href="#" class="reveal" style="background-image: url(http://lorempixel.com/output/technics-q-g-256-256-5.jpg);">
    <span style="background-image: url(http://lorempixel.com/output/food-q-c-256-256-9.jpg);" />
</a>

CSS

a.reveal {
    display: block;
    height: 256px; width: 256px;
    position: relative;
}
a.reveal span {
    display: none;
    background-repeat: no-repeat;
    position: absolute;
}

a.reveal:hover span {
    display: block;
    left: 0; top: 0;
    height: 100%; width: 100%;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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