JavaScript代码可在JSFiddle中使用,但不能在浏览器中使用

时间:2019-06-02 20:34:20

标签: javascript html css jsfiddle

使用基于Github SVG的现有JSFiddle;代码在Fiddle中进行测试时完全按照预期的方式工作,但是在浏览器中,SVG图像的指定区域在悬停时未显示颜色。尝试将JS嵌入HTML中,但错误仍然存​​在。 HTML块中的错误在哪里?

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(styles.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]]);
        }       
    });
});

1 个答案:

答案 0 :(得分:1)

问题在于,在执行脚本时,DOM尚未完全加载并且可以进行操作。

您可以尝试在结束</body>之前移动脚本,或将代码包装在

$(document).ready(function() {
    // Your code
});