我有一个HTML符号
phone.setowners
我想用作光标。我很熟悉通过JQuery更改光标,如下所示:
<symbol id="arrow" viewBox="0 0 8.4666659 8.4666659">
<g transform="translate(0,-288.53334)">
<path style="fill:none;stroke:#000000;stroke-width:0.48417112;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;" d="m 0.17215798,288.70836 8.05225192,8.04935"></path>
<path style="fill:none;stroke:#000000;stroke-width:0.48417112;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;" d="m 8.2221335,293.64243 0.00228,3.11528 -3.1283502,2.2e-4"></path>
</g>
</symbol>
但是如何为body.css('cursor', `wait`);
元素执行此操作?
答案 0 :(得分:18)
您可以设置两个<svg>
元素来定义SVG符号,另一个元素来保存元素。然后使用Javascript,您可以设置一个事件监听器,并在用户的光标移动时更改整个<svg>
(持有您的元素的那个)的位置。此外,我已使用CSS属性cursor: none
隐藏了默认浏览器光标。这是一个有效的代码:
document.addEventListener('mousemove', function(e) {
let newTransformRule = 'translate(' + (e.pageX - 360) + 'px, ' + (e.pageY - 115) + 'px)';
document.querySelector('#arrowCanvas').style.transform = newTransformRule;
});
body {
cursor: none;
}
<svg>
<symbol id="arrow" viewBox="0 0 8.4666659 8.4666659">
<g transform="translate(0,-288.53334)">
<path style="fill:none;stroke:#000000;stroke-width:0.48417112;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;" d="m 0.17215798,288.70836 8.05225192,8.04935"></path>
<path style="fill:none;stroke:#000000;stroke-width:0.48417112;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;" d="m 8.2221335,293.64243 0.00228,3.11528 -3.1283502,2.2e-4"></path>
</g>
</symbol>
</svg>
<svg id="arrowCanvas" width="100" height="60">
<use href="#arrow" width="100" height="50"/>
</svg>
您必须调整newTransformRule
中的值,以使用默认光标将自定义光标居中。删除CSS规则以进行调整。
该代码适用于Firefox,Chrome和Edge。
答案 1 :(得分:0)
@Ivan回答很好,但是,这样做会更好。
我刚做了一些改变
document.addEventListener('mousemove', function(e) {
let newTransformRule = 'translate(' + (e.pageX - 380) + 'px, ' + (e.pageY - 60) + 'px)';
document.querySelector('#arrowCanvas').style.transform = newTransformRule;
});
&#13;
body {
cursor: none;
}
#arrowCanvas {
width: 100%;
height: 100%;
position: absolute;
z-index: -1;
}
&#13;
<svg id="arrowContainer">
<symbol id="arrow" viewBox="0 0 8.4666659 8.4666659">
<g transform="translate(0,-288.53334)">
<path style="fill:none;stroke:#000000;stroke-width:0.48417112;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;" d="m 0.17215798,288.70836 8.05225192,8.04935"></path>
<path style="fill:none;stroke:#000000;stroke-width:0.48417112;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;" d="m 8.2221335,293.64243 0.00228,3.11528 -3.1283502,2.2e-4"></path>
</g>
</symbol>
</svg>
<svg id="arrowCanvas" width="100" height="60">
<use href="#arrow" width="100" height="50"/>
</svg>
&#13;