考虑到Paulie_D关于 SVG 的评论后,我编写了一个使用 SVG 来替代经典图像映射的方法。两者都工作得很好,但在响应能力方面,SVG 版本显然更胜一筹。两个版本都使用 - 属性在锚点和相应的工具提示之间建立连接href。这两种解决方案都适用于普通 JavaScript,无需额外的库。
优点
超文本标记语言
<svg id="map" version="1.1" viewBox="0 0 300 300">
<image width="300" height="300" xlink:href="http://placehold.it/300"/>
<a xlink:href="#t_1">
<rect x="50" y="50" width="50" height="50" />
</a>
<a xlink:href="#t_2">
<rect x="150" y="150" width="50" height="50" />
</a>
</svg>
<div class="t" id="t_1">Tooltip 1</div>
<div class="t" id="t_2">Tooltip 2</div>
Run Code Online (Sandbox Code Playgroud)
CSS
html, body {
width: 100%;
margin: 0;
padding: 0;
}
svg {
display: block;
width: 80%;
max-width: 300px;
margin: 0 auto;
}
svg rect {
fill: white;
opacity: 0.1;
transition: all 0.2s linear;
}
svg rect:hover {
opacity: 0.8;
}
.t {
opacity: 0;
position: absolute;
left: 0;
top: 0;
transition: opacity 0.4s linear;
}
.t.active {
opacity: 1;
}
Run Code Online (Sandbox Code Playgroud)
JavaScript*
var map = document.getElementById('map');
var areas = map.getElementsByTagName('a');
var offset = { left: 30, top: 70 };
for (var i = 0; i < areas.length; i++) {
areas[i].onmouseover = function() {
// get child element
var c = this.firstElementChild;
// get tooltip
var t = document.getElementById(this.getAttribute('xlink:href').substr(1));
// set styles
t.style.left = (map.offsetLeft + parseInt(c.getAttribute('x')) + offset.left) + 'px';
t.style.top = (map.offsetTop + parseInt(c.getAttribute('y')) + offset.top) + 'px';
// show it
t.classList.toggle('active');
}
areas[i].onmouseout = function() {
// get tooltip
var t = document.getElementById(this.getAttribute('xlink:href').substr(1));
// hide it
t.classList.toggle('active');
}
}
Run Code Online (Sandbox Code Playgroud)
笔记
演示
超文本标记语言
<img src="http://placehold.it/300" alt="" usemap="#map">
<map id="map" name="map">
<area shape="rect" coords="0,0,50,50" href="#t_1" alt="Tip 1" data-left="80px" data-top="80px" />
<area shape="rect" coords="100,100,150,150" href="#t_2" alt="Tip 2" data-left="180px" data-top="180px" />
</map>
<div class="t" id="t_1">Tooltip 1</div>
<div class="t" id="t_2">Tooltip 2</div>
Run Code Online (Sandbox Code Playgroud)
CSS
.t {
opacity: 0;
position: absolute;
left: 0;
top: 0;
transition: opacity 0.4s linear;
}
.t.active {
opacity: 1;
}
Run Code Online (Sandbox Code Playgroud)
JavaScript*
var areas = document.getElementById('map').children;
for (var i = 0; i < areas.length; i++) {
areas[i].onmouseover = function() {
var t = document.getElementById(this.hash.substr(1));
t.style.left = this.dataset.left;
t.style.top = this.dataset.top;
t.classList.toggle('active');
}
areas[i].onmouseout = function() {
var t = document.getElementById(this.hash.substr(1));
t.classList.toggle('active');
}
}
Run Code Online (Sandbox Code Playgroud)
笔记
data-*,解耦 JavaScript(不幸的是,您无法使用offsetLeft/Top和确定基于 -element 的位置area) - 但是您可以使用coords-attribute来计算它演示
* 在这两个示例中,JavaScript 都可以改进,例如将工具提示元素存储在变量中,而不是一直重新查询它们。
| 归档时间: |
|
| 查看次数: |
935 次 |
| 最近记录: |