<分区>
<分区>
使用基于 Github SVG 的现有 JSFiddle;在 Fiddle 中测试时代码完全按预期工作,但在浏览器中,SVG 图像的指定区域在悬停时不显示颜色。尝试将 JS 嵌入到 HTML 中,但错误仍然存在。 HTML block 中的错误在哪里?
HTML:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="svgjs.js"></script>
</head>
<body>
<span class="map"></span>
</body>
</html>
CSS (样式.css)
.map {
max-width: 100%;
}
.map path {
fill: #e0bd3f;
stroke: none;
cursor: no-drop;
transition: fill 300ms ease;
}
.map .active, .map .active path {
cursor: pointer;
}
.map .active.group0, .map .active.group0 path {
fill: cornflowerblue;
}
.map .active.group1, .map .active.group1 path {
fill: indianred;
}
.map .active.group2, .map .active.group2 path {
fill: forestgreen;
}
.map .active.group3, .map .active.group3 path {
fill: gold;
}
.map .active.group4, .map .active.group4 path {
fill: lightsalmon;
}
Javascript (svgjs.js):
var regions = [
['gb', 'fr', 'de', 'es', 'it', 'nl', 'ie', 'be', 'pt', 'ch'],
['ca', 'us', 'mx'],
['no', 'fi', 'se'],
['au', 'nz', 'in', 'cn', 'jp'],
['za', 'na', 'bw', 'zw', 'mz', 'ao', 'zm', 'tz', 'mg']
];
$(document).ready(function() {
$('.map').load('https://raw.githubusercontent.com/benhodgson/markedup-svg-worldmap/master/map.svg');
$('.map').on('mouseleave', 'path, g', function() {
// When the mouse leaves an area, remove its classes
$('.map .active').removeClass('active');
$.each(regions, function(index, region) {
$('group' + index).removeClass('group' + index);
});
}).on('mouseenter', 'path, g', function() {
// When the mouse enters an area, check to see if it's in a region
var thisCountry = $(this).attr('cc');
$.each(regions, function(regionIndex, region) {
if (region.indexOf(thisCountry) > -1) {
// Highlight all countries in the region
$.each(region, function(index, country) {
$('.map [cc="' + country + '"]').addClass('active').addClass('group' + regionIndex);
});
}
});
}).on('click', 'path, g', function() {
// Show the region name when a country is clicked
if ($(this).attr('class')) {
alert(regionNames[$(this).attr('class').match(/[0-9]+/)[0]]);
}
});
});
最佳答案
问题是在脚本执行时,DOM 没有完全加载并准备好进行操作。
您可以尝试在结束前移动您的脚本 </body>
, 或者将您的代码包装在
$(document).ready(function() {
// Your code
});
关于Javascript 代码在 JSFiddle 中工作,但在浏览器中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56418762/