如何将单个图像分成不同的链接

时间:2015-03-08 08:19:06

标签: jquery css image web

我在网站上有一个30(宽)px,130(高)px图像。我想从这张图片中创建4个不同的链接。例如,我想为一个链接创建0到32px的部分,为另一个链接创建33px到65px的部分,就像这样。是否可以使用jquery,css或任何Idea?

3 个答案:

答案 0 :(得分:2)

尝试



$(function() {
  var img = $("img")
  , parts = img.height() / 4
  , links = ["a", "b", "c", "d"]
  , regions = $.makeArray(Array(img.height()))
    .map(function(section, key) {
      return key + 1
    })
  , sections = [];

  links.forEach(function(value, key) {
    sections.push(regions.splice(0, Math.floor(Math.round(parts))))
  })

  $("img").on("click", function(e) {
    var res = $.map(sections, function(value, key) {
      return $.inArray(e.clientY, value) !== -1 ? key : null
    })[0];
    console.log("section: " + links[res])
  });
});

img {
  background: sienna;
  width: 30px;
  height: 130px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<img src="" />
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用地图。这是一个example

<map name="bigthings" id="bigthings">
  <area shape="rect" coords="35,4,205,108"
      href="http://en.wikipedia.org/wiki/Australia's_Big_Things"
      alt="Australia's Big Things (on Wikipedia)"/>
  <area shape="rect" coords="136,163,255,230"
      href="http://vwkombi.com/"
      alt="The VW Kombi, another Aussie icon"/>
</map>
⋮
<p><img src="giant-prawn.jpg" alt="The Giant Prawn at Ballina"
usemap="#bigthings"/></p>

答案 2 :(得分:1)

只需将图片用作容器的背景,并在其上放置<a>元素:

#container {
    width: 300px;
    height: 85px;
    background: url('http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png') no-repeat;
}

#part1, #part2, #part3 {
    display: table-cell;
    width: 100px;
    height: 85px;
}

HTML:

<div id="container">
    <a id="part1" href="http://stackoverflow.com/" />
    <a id="part2" href="http://stackexchange.com" />
    <a id="part3" href="http://github.com"/>
</div>

http://jsfiddle.net/e2epotyg/1/