更改图像映射的图像类别

change class on image for image map

本文关键字:图像 映射      更新时间:2024-05-24

我知道有人问过很多类似的问题,但我似乎无法使用任何解决方案。。我有这个位于div中的图像映射:(别管坐标,它们现在不正确)

<div class="spinner">
 <img src="test.gif"  alt="spinner" id="map" class="map" usemap="#spinnermap">
 <map name="spinnermap">
   <area shape="poly" coords="0,0,82,126" href="" id="systemmap" alt="System">
   <area shape="poly" coords="90,58,3" href="" id="rolemap" alt="Role">
   <area shape="poly" coords="124,58,8" href="" id="phasemap" onclick="createTable();" alt="Phase">
 </map>
</div>

现在,当最后一个poly被点击时(或者任何一个,但只是为了例如),我需要map img有一个不同的css类,这样class="map"就被class="phasemap"取代了。(我在css中有一个精灵,你可以看到:)

我试过这个:

$('#phasemap').click(function(){
    $(this).find("#map").toggleClass('phasemap map');
}); 

但它似乎并没有起到作用。。我确信我有一个打字错误或更多-我对这个js/jq东西很陌生:)

编辑:我刚刚意识到,也许这意味着地图是在JS中创建的。。所以我还需要知道把jq的东西放在哪里(在地图下面,或者在.js文件中放在哪里?:)

我的JS:

function createSpinner() {
    var spinner = '<div class="spinner">';
    spinner += '<img src="filler.png" id="map" class="map" alt="Spinner"  Usemap="#spinnermap" border="0" />';
    spinner += '<map name="spinnermap">';
    spinner += '<area shape="poly" coords="5,25 51,60 110,25 51,2 8,25" href="#" onclick="createTable();" alt="Role">';
    spinner += '<area shape="poly" coords="5,25 8,66, 15,89 55,112 55,66 5,25"  href="#" onclick="createTable();" alt="System">';
    spinner += '<area shape="poly" coords="55,112 89,108 118,59 110,25 51,66 55,112" id="phasemap" href="#" onclick="createTable();" alt="Phase">';
    spinner += '</map>';
    spinner += '</div>';
    return spinner;
}
$('#phasemap').click( function() {
    $("#map").toggleClass('phasemap map');
    return false;
}); 

和css:

.map {
    width: 117px;
    height: 119px;
    background: url('spinner.png');
    background-repeat: no-repeat;
    background-position: 0px 0px;
}
.rolemap {
    background-position: 0px 0px;
}   
.systemmap {
    background-position: 0px -124px;
}
.phasemap {
    background-position: 0px -248px;
}

您必须将$('#map')用作selector,而不是$(this).find("#map"),因为您的imgphasemap之外试试这个,

$('#phasemap').click(function(){
   $("#map").toggleClass('phasemap map');
   // Use #map directly it is not children of #phasemap
});// don't use colon here

已更新,您必须在toggleClass之后使用return false;,以防止area的默认工作,如

$('#phasemap').click(function(){
   $("#map").toggleClass('phasemap map');
   return false;// use return false or event.preventDefault() here
});

演示中,您可以在console中看到image classtoggling

从你的edited question你应该使用jquery version >= 1.9一个使用on()类似

$(document).on('click','#phasemap',function(){
   $("#map").toggleClass('phasemap map');
   return false;
}); 

你要检查createSpinner()是否有效。通过在firebug 中检查

var a=0;
function yourfunctionname(){
  if(a == 0){
   $("#map").attr('class','');
   $("#map").attr('class','phasemap map');
   a=1;
   return false;
  }
  else{
   $("#map").attr('class','');
   $("#map").attr('class','map');
   a=0;
   return false;
   }
 // your function code 
}