Javascript 为什么要删除悬停状态行为?
我有一个D3生成的地图,它需要能够动态更改绘制路径的填充元素。原始路径生成并分配一类“边界”。当用户将光标悬停在国家上时,悬停行为设置为将国家变为黄色。但是,如果我随后去动态更改国家/地区的填充颜色,例如使用d3.selectAll-我简化了下面的示例,以便通过取消注释最后一部分模拟此行为,则悬停行为停止工作。类没有更改,那么为什么悬停行为现在没有发生。。有解决办法吗 CSS JavascriptJavascript 为什么要删除悬停状态行为?,javascript,css,d3.js,svg,Javascript,Css,D3.js,Svg,我有一个D3生成的地图,它需要能够动态更改绘制路径的填充元素。原始路径生成并分配一类“边界”。当用户将光标悬停在国家上时,悬停行为设置为将国家变为黄色。但是,如果我随后去动态更改国家/地区的填充颜色,例如使用d3.selectAll-我简化了下面的示例,以便通过取消注释最后一部分模拟此行为,则悬停行为停止工作。类没有更改,那么为什么悬停行为现在没有发生。。有解决办法吗 CSS Javascript const countryMap = {}; const FILE = `aus.ge
const countryMap = {};
const FILE = `aus.geojson`; // the file we will use
var svg = d3
.select('div.country__map')
.append('svg')
.attr('width',200)
.attr('height',200)
.attr('preserveAspectRatio', 'xMinYMin meet')
.attr('viewBox','770 270 200 150')
d3.json(FILE).then(function (outline) {
countryMap.features = outline.features;
// choose a projection
const projection = d3.geoMercator();
// create a path generator function initialized with the projection
const geoPath = d3.geoPath().projection(projection);
drawOutline();
function drawOutline() {
svg
.selectAll('path.boundaries') // CSS styles defined above
.data(countryMap.features)
.enter()
.append('path')
.attr('class', 'boundaries')
.attr('d', geoPath)
// .style('fill', d => {
// return 'green';
// })
}
})
正如@Michael提到的,最好使用js手动添加或删除类 D3为我们提供了mouseover和mouseout事件,可用于添加和删除类 在hover上,我们将在元素上应用“active”类
svg
.selectAll('path.boundaries')
.data(countryMap.features)
.enter()
.append('path')
.attr('class', 'boundaries')
.attr('d', geoPath)
.on('mouseover', function () {
d3.select(this).classed("active", true)
})
.on('mouseout', function () {
d3.select(this).classed("active", false)
})
我们还需要根据这些变化来更新CSS。
您可以将CSS更新为:
.boundaries{
fill:green;
}
.boundaries.active{
fill:yellow;
}
SVG子元素上的悬停状态有很多问题-最好使用JavaScript手动更改类。
.boundaries{
fill:green;
}
.boundaries.active{
fill:yellow;
}