使用图像映射来显示和隐藏div元素

时间:2016-02-09 09:19:40

标签: jquery html imagemap

到目前为止这是我的代码..

DEMO

我希望用户只有在点击蓝色圆圈等时才能显示蓝色文字......

我想我只需要更改div元素的属性,但我对jQuery不太满意,并且不确定最优雅的方法。

HTML

<img src="http://www.j-creative.biz/wp-content/uploads/2015/10/primary-colours-300x171.png" usemap="#test1" alt="" />
<map id="primarytest" name="test1">
  <area shape="circle" coords="50,75,50" href="#" item="red"/>
  <area shape="circle" coords="150,75,50" href="#" item="blue"/>
  <area shape="circle" coords="250,75,50" href="#" item="yellow"/> 
</map>

<div class="one" style="display:none" id="redtext">
<h5>
HelloRed
</h5>
</div>
<div class="one" style="display:none" id="bluetext">
<h5>
HelloBlue
</h5>
</div>
<div style="display:none" id="yellowtext">
<h5>
HelloYellow
</h5>
</div>

的jQuery

$('[item="red"]).click(function() {
$(".one").hide();
    $("#redtext").show();
    return false;
});

1 个答案:

答案 0 :(得分:1)

您当前的代码只是缺少选择器的结束语和小提琴的jQuery。修复这些问题并且有效:

Updated fiddle

话虽如此,您可以通过遵循DRY原则来改进逻辑。为此,您可以在area元素和data属性上放置一个公共类,以指定在单击时应显示的元素。然后,您可以在所有这些上使用单个事件处理程序。试试这个:

<img src="http://www.j-creative.biz/wp-content/uploads/2015/10/primary-colours-300x171.png" usemap="#test1" alt="" />
<map id="primarytest" name="test1">
    <area shape="circle" coords="50,75,50" href="#" class="circle" data-target="redtext" />
    <area shape="circle" coords="150,75,50" href="#" class="circle" data-target="bluetext" />
    <area shape="circle" coords="250,75,50" href="#" class="circle" data-target="yellowtext" />
</map>

<div class="one" id="redtext">
    <h5>HelloRed</h5>
</div>
<div class="one" id="bluetext">
    <h5>HelloBlue</h5>
</div>
<div class="one" id="yellowtext">
    <h5>HelloYellow</h5>
</div>
$('.circle').click(function(e) {
    e.preventDefault();
    $(".one").hide().filter('#' + $(this).data('target')).show();
});

Example fiddle