3

我无法在传单多边形上重置样式。悬停时效果很好,但是当setStyle我停止悬停时重置它不起作用。我收到Uncaught TypeError: Object [object Object] has no method 'resetStyle'。我了解该错误的含义,但我不知道如何正确执行此操作。

提前致谢。

$.getJSON('geoJSON.json', function (json) {
    L.geoJson(json, {
        ...
        onEachFeature: function (feature, layer) {
            var defaultStyle = layer.style;

            layer.on('mouseover', function (e) {
                this.setStyle({
                    color: '#2262CC',
                    weight: 3,
                    opacity: 0.6,
                    fillOpacity: 0.65,
                    fillColor: '#2262CC'
                });
            });
            layer.on('mouseout', function (e) {
                this.resetStyle();
            });
        }
    }).addTo(map);
});
4

2 回答 2

4

上面的代码失败,因为 resetStyle 函数可以在 geojson 层中找到,而不是在“this”指向的层中。

此外,geojson 图层需要为默认样式设置样式路径选项,才能使 resetStyle 正常工作。

$.getJSON('geoJSON.json', function (json) {
    var geojson = L.geoJson(json, {
        ...
        style: <default style here>
        onEachFeature: function (feature, layer) {
            var defaultStyle = layer.style;

            layer.on('mouseover', function (e) {
                this.setStyle({
                    color: '#2262CC',
                    weight: 3,
                    opacity: 0.6,
                    fillOpacity: 0.65,
                    fillColor: '#2262CC'
                });
            });
            layer.on('mouseout', function (e) {
                geojson.resetStyle();
            });
        }
    }).addTo(map);
});
于 2013-12-04T09:04:07.743 回答
2

这可能是上下文问题:

$.getJSON('geoJSON.json', function (json) {
    L.geoJson(json, {
        ...
        onEachFeature: function (feature, layer) {
            var defaultStyle = layer.style,
                that = this;//NEW

            layer.on('mouseover', function (e) {
                this.setStyle({
                    color: '#2262CC',
                    weight: 3,
                    opacity: 0.6,
                    fillOpacity: 0.65,
                    fillColor: '#2262CC'
                });
            });
            layer.on('mouseout', function (e) {
                that.resetStyle(); //NEW
            });
        }
    }).addTo(map);
});
于 2013-05-28T08:51:45.483 回答