2

我有一个代码可以在我的网站上工作。我目前正在使用带有 href="#image1" 锚标记的文本链接将特定 div 标记中的图像替换为另一个图像。

这背后的原理是,当您单击地址的文本时,地图会变为该特定地址的地图图像。但是,我目前在图像上使用渐变叠加,实际地图是使用 css 背景图像编码的。

.map-grad {
    background-image: url(../img/map.png);
    -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src=//ssl.gstatic.com/s2/oz/images/local/map_gradient.png, sizingMethod=scale)";
    background: -webkit-linear-gradient(top, transparent 0%, transparent 66%, rgba(0, 0, 0, 0.294) 77%, rgba(0, 0, 0, 0.497) 91%, rgba(0, 0, 0, 0.7) 100%), url(../img/map.png);
    background: -moz-linear-gradient(top, transparent 0%, transparent 66%, rgba(0, 0, 0, 0.294) 77%, rgba(0, 0, 0, 0.497) 91%, rgba(0, 0, 0, 0.7) 100%), url(../img/map.png);
    background: -ms-linear-gradient(bottom, transparent 0%, transparent 66%, rgba(0, 0, 0, 0.294) 77%, rgba(0, 0, 0, 0.497) 91%, rgba(0, 0, 0, 0.7) 100%), url(../img/map.png);
    background: -o-linear-gradient(bottom, transparent 0%, transparent 66%, rgba(0, 0, 0, 0.294) 77%, rgba(0, 0, 0, 0.497) 91%, rgba(0, 0, 0, 0.7) 100%), url(../img/map.png);
    background: linear-gradient(bottom, transparent 0%, transparent 66%, rgba(0, 0, 0, 0.294) 77%, rgba(0, 0, 0, 0.497) 91%, rgba(0, 0, 0, 0.7) 100%), url(../img/map.png);
    background-position: center;
    height: 250px;
    max-height: 250px;
    max-width: 1600px;
}

我的 jQuery 是:

 var itemInfo = { // Initialise the item information
      img1: ['/img/map.png', ''],
      img2: ['/img/map2.jpg', ''],
};

$(function() {
      $('#maps a').click(function() { // When an item is selected
            var id = $(this).attr('href').replace(/#/, ''); // Retrieve its ID
            $('#info img').attr('src', itemInfo[id][0]); // Set the image
            $('#info p').text(itemInfo[id][1]); // And text
            return false; // Prevent default behaviour
      });
});

图片链接格式如下:

<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>

被替换的实际图像如下:

<div class="map-grad">
    <div id="info">
        <img src="/img/map.png">
    </div>
</div>

任何人都可以帮助我并建议一种通过css背景图像替换这些图像的方法。我的一个想法是从 .map-grad 中删除 background-image css 标签,然后简单地将其如下所示:

<div id="info">
<div class="map-grad" style="background-image: url(../img/map.png);"></div>
</div>

并编写jQuery代码来替换css url而不是它当前替换的img src?有什么想法和帮助吗?谢谢

4

1 回答 1

1

如果您需要替换所有图像,我能想到的唯一方法是

$.each($('*'), function( index, element ) {
   var element = $(element);
   if(element.css('background-image') === 'YourMap.png') {
      element.css('background-image', 'newMap.png');
   }
});

尽管使用类或其他东西而不是 * 会更好

编辑:如果您对所有图像都有课程,则只需执行此操作

$('.myClass').css('background-image', 'newImg.png')
于 2013-06-16T12:27:46.913 回答