javascript selecting a custom cursor (svg)

2019-04-14 23:33发布

问题:

I'm dynamically changing a cursor to a local svg on hover with

$(element).on('mouseover', function () {
    $(this).css('cursor', 'url(svgs/pointer.svg) 9 30 auto');
};

Thats working fine but I'd like to select that svg to manipulate its fill color.

Is there any way to do this so I don't have to make a bunch of different svgs with different fills?

Thanks

回答1:

You can use inline SVG. Just open your SVG file with your text editor. Copy the XML and use it instead. Just change the fill value and reassign it to the element.

cursor: url('data:image/svg+xml;utf8,<svg fill="%23FF0000" height="48" viewBox="0 0 24 24" width="48" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"/><path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/></svg>') 24 24, auto;

When using this technique you should escape special chars in the data. Some people prefer to Base64 their images but for SVG you don't need it. In the example above I only had to replace # in the fill value with %23.