我想在我给 span 元素的字符上画圆圈。我已经让它与一个元素一起工作(参见注释代码)。我只想按每个 span 元素来做。 首先,我首先尝试用悬停来做,但我已经失败了。在调用 draw 函数时应该发生悬停。
function draw() {
ctx.save();
ctx.translate(plotX1, 0);
$("p").find("span").hover(function(){
console.log("hover");
var x = $(this).offsetLeft;
var y = $(this).offsetTop;
y += $(this).offsetHeight;
ellipse(ctx, x, y, 10);
ctx.strokeStyle = "rgba(200, 0, 0, 50)";
ctx.stroke();
});
ctx.restore();
/*
// this worked on the element with id s2
var x = s2.offsetLeft;
var y = s2.offsetTop;
y += s2.offsetHeight;
ctx.fillStyle = "rgb(0, 250, 0)";
//ctx.fillRect(x, y, 10, 10);
ellipse(ctx, x, y, 10);
ctx.strokeStyle = "rgba(200, 0, 0, 50)";
ctx.stroke();
*/
}
最佳答案
这至少更接近您正在寻找的东西,悬停的工作,它绘制了圆圈,但它也连接了圆圈,应该能够轻松解决这个问题(也许使用 ctx.moveTo()
)
function draw() {
$('#canv').attr('width', $('p').width()).attr('height', $('p').height());
//ctx.translate(plotX1, 0);
$('p span').hover(function() {
ctx.save();
var x = this.offsetLeft,
y = this.offsetTop;
y += this.offsetHeight / 2;
//ctx.moveTo(x, y);
ellipse(ctx, x, y, 10);
ctx.strokeStyle = "rgba(200, 0, 0, 50)";
ctx.stroke();
ctx.restore();
}, function() {
clearCanvas(ctx);
});
}
我认为主要问题可能是您在哪里使用 $(this).offsetLeft;
获取偏移量(其中 $(this)
是一个 jQuery 对象) . this.offsetLeft
有效。
深思熟虑:
不确定您的最终目标是什么,但您也可以使用 CSS 在 span 周围做一个简单的 box-shadow
p span:hover {box-shadow:0 0 0 2px #f00;border-radius:10px;}
关于javascript - 在每个 span 元素上画圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8683604/