2012-08-12 106 views
0

我有一个图像,我正在使用图像映射。当根据地图悬停在图像的一部分上时,我希望图像更改,但我不确定如何使用jQuery执行此操作。这里是我试图代码:使用jQuery和图像映射关于悬停更改图像

HTML:

<div class="img-center"> 
    <img src="img-src_off.jpg" usemap="#Map" class="feature-image" border="0" /> 
    <map name="Map" id="Map"> 
     <area shape="rect" coords="77,461,391,492" href="#" target="_blank" 
      class="link-1" /> 
     <area shape="rect" coords="557,461,855,490" href="#" target="_blank" 
      class="link2" /> 
    </map> 
</div> 

JS:

注:这是JS我已经尝试,但错误抛出(在下面列出的错误)和我现在不知道该怎么做。如果我可以找到没有问题的代码,则不必使用此代码。

var $j = jQuery.noConflict(); 
    $j(document).ready(function() { 
    $j.preLoadImages("img_src_01.jpg", 
        "img_src_02.jpg" 
    ); 

    $j(".link1").hover(function(){ 
     this.src = this.src.replace("_off","_01"); 
     }, 
     function(){ 
     this.src = this.src.replace("_01","_off"); 
     } 
    ); 

      $j(".link2").hover(function(){ 
     this.src = this.src.replace("_off","_02"); 
     }, 
     function(){ 
     this.src = this.src.replace("_02","_off"); 
     } 
    ); 
    }); 

    (function(j$) { 
    var cache = []; 
    $j.preLoadImages = function() { 
     var args_len = arguments.length; 
     for (var i = args_len; i--;) { 
     var cacheImage = document.createElement('img'); 
     cacheImage.src = arguments[i]; 
     cache.push(cacheImage); 
     } 
    } 
    }); 

我看到的错误如下:

TypeError: this.src is undefined 
[Break On This Error] 

this.src = this.src.replace("_off","_01"); 

(this error repeats itself on every hover) 

而这个错误:

TypeError: $j.preLoadImages is not a function 
[Break On This Error] 

"img_src_02.jpg" 

请回答的时候,因为我不是在Javascript很流利提供范例。

回答

1

To write a jQuery plugin, start by adding a new function property to the jQuery.fn object where the name of the property is the name of your plugin:

尝试以下操作:

(function($j) { 
    $j.fn.preLoadImages = function() { 
     //... 
    } 
})(jQuery); 
+0

这仍然抛出了同样的错误。 – L84 2012-08-12 19:25:10

+0

@Lynda因为它是jQuery对象的方法之一,所以您应该选择一个元素并制作一个jQuery对象,我会看到'$(selector).preLoadImages()' – undefined 2012-08-12 19:27:28

+0

。我认为整个脚本需要重新编写,但由于缺乏知识,我自己无法做到这一点。 – L84 2012-08-12 19:30:26