如何在javascript中选择带有类名的SVG路径

时间:2015-11-30 18:29:09

标签: javascript css svg

我有一个SVG,想要在另一个元素悬停时改变元素的样式。在这个例子中,当我将鼠标悬停在“ring_three_fill”上时,我将使用“ring_three_border”的样式进行更改。我尝试了两种方法:css和javascript。这两种方法都不起作用。既然它不在css中工作,有没有办法在javascript中选择具有类名的路径,这些路径在悬停时会发生变化?

<path id="ring_three_fill" class="ring-fill hide" opacity="0.5" fill="#66BCEA" d="M563.6,255.3c0.1,0,0.2,0,0.2,0c0-3.5,0.3-7.1-0.1-10.6
    c-1.3-12-5.6-22.9-13.1-32.4c-10.5-13.3-18.5-28-23.4-44.3c-1.6-5.4-3.7-10.6-6.1-15.6c-5-10.8-11.9-19.9-23.2-24.8"/>
<path id="ring_three_border" class="ring-border hide" opacity="0.5" fill="#66BCEA" d="M537.4,265.2c-0.9-12.9-5-24.5-12.5-35.1"/>

CSS:

path.ring-fill:hover path.ring-border {
            transform: scale(1.2,1.2);
        }

使用Javascript:

var fill = document.getElementsByClassName("ring_fill");
        fill.onmouseover = function() {
            document.getElementsByClassName("ring-border").attr("style", "transform: scale(1.2,1.2);")
        };

1 个答案:

答案 0 :(得分:0)

我认为这就是你想要的。使用纯JavaScript。

var proximity = 2;
var steps = parseInt(5 / (proximity * 2), 10);

function sortPaths(list) {
    var sizes = [].map.call(list, function (path) {
        return {
            el: path,
            length: path.getTotalLength()
        };
    });
    return sizes.sort(function (a, b) {
        return a.length > b.length;
    }).map(function (path) {
        return path.el;
    });
}

function reset(from, to, arr) {
    for (var i = from; i < to; i++) {
        arr[i].setAttribute("style", "transform: scale(1,1);");
    }
}

function attach(rings, i) {
    var start = proximity * -1;
    return function () {
        for (var j = start; j < proximity; j++) {
            var el = rings[i + j];
            if (!el) continue;
            var step = (j == 0 ? 13 : 10 + (j / 3 * 4));
            var transform = ['transform: scale(', ',', ');'].join(step / 10);
            el.setAttribute("style", transform);
        }
        reset(i + proximity, rings.length, rings);
    }
}

var rings = sortPaths(document.querySelectorAll('path.ring-border'));
for (var i = 0; i < rings.length; i++) {
    rings[i].addEventListener('mouseenter', attach(rings, i));
    rings[i].addEventListener('mouseleave', function () {
        this.setAttribute("style", "transform: scale(1,1);");
    });
}

jsFiddle:http://jsfiddle.net/2nm5j0jq/

您可能需要稍微配置一下,但这应该非常接近您想要的。