简体   繁体   English

Javascript添加具有onmouseover属性的area元素

[英]javascript to add area element with onmouseover attribute

I am trying to add area elements to an image map dynamically. 我正在尝试将区域元素动态添加到图像地图。 The image is set to display transparently superimposed over a canvas. 图像设置为透明叠加显示在画布上。 My goal is to write text on the canvas, use the same coordinates to create the area element on the map, and draw a rectangle on the canvas surrounding the text when the user hovers over the text. 我的目标是在画布上书写文本,使用相同的坐标在地图上创建area元素,并在用户将鼠标悬停在文本上方时在画布上围绕该文本绘制一个矩形。 (Ultimately I want it to trigger a tooltip, too.) I have done this already with the same map and canvas setup using area elements hardcoded in HTML. (最终,我也希望它触发工具提示。)我已经使用HTML硬编码的区域元素通过相同的地图和画布设置完成了此操作。

My problem is that I can create the area, appendChild it to the map element and add attributes. 我的问题是我可以创建该区域,将其appendMap到map元素并添加属性。 However, mousing over the text never triggers the function call to draw the rectangle. 但是,将鼠标悬停在文本上绝不会触发绘制矩形的函数调用。

The function used to add the areas to the map (shown as cMap) is "addArea", and the function to draw the rectangle on the canvas (context is ctx) is "labelHover". 用于将区域添加到地图的功能(显示为cMap)为“ addArea”,用于在画布上绘制矩形(上下文为ctx)的功能为“ labelHover”。 I have tried every different syntax I have seen demonstrated for adding the .onmouseover attribute to the area, but the alert in the labelHover function never triggers. 我已经尝试过将.onmouseover属性添加到该区域所展示的各种语法,但是labelHover函数中的警报从未触发。

function addArea(pX, lY, idX, tipText) {
    var labelArea = document.createElement('area');
    cMap.appendChild(labelArea);
    labelArea.className = "labelArea";
    var tlTipID = "tlTip" + idX;
    labelArea.id = tlTipID;
    labelArea.shape = "rect";
    areaCoords = pX + "," + (lY + 42) + "," + (pX + 100) + "," + (lY + 54);
    labelArea.coords = areaCoords;
    // alert(labelArea.coords);
    labelArea.onmouseover = function(){labelHover(pX, lY+42)};
    labelArea.onmouseleave = function(){labelLeave(pX, lY+42)};
}

and

function labelHover(ulx,uly) {
   ctx.lineWidth = "1";
   ctx.strokeStyle = "#ff0000";
   ctx.strokeRect(ulx,uly,100,12);
   alert(ulx);
}

Thanks for any help. 谢谢你的帮助。

try this: 尝试这个:

labelArea.setAttribute('onmouseover', "labelHover('" + pX + "," + (lY+42) + "')");
labelArea.setAttribute('onmouseout', "labelLeave('" + pX + "," + (lY+42) + "')");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM