javascript - 试图让 onmouseenter 和 onmouseout 在 dom 中处理新的 img
问题描述
环境: Safari 110.0.1、OSX (MacOS) 10.12.6
我正在研究图像库类型的显示。有一个元素通过 Javascript 加载了图像;我希望该元素在 onmouseenter 和 onmouseout 上具有功能。
似乎我在创建 img 元素时无法添加这些元素,因为图像未加载,并且我读到(在某处,哈哈,这是漫长的一天)必须先加载一个元素才能加载为其附加功能。我确实在 HTML 中尝试过;没有喜悦。
所以我有一个计时器,我试图将它附加在那里,但这也不起作用 - 这些函数永远不会被调用。
我尝试在页面加载后启动计时器,但是,这不起作用 - over/out 功能仍然不会触发。计时器肯定正在运行,如果页面缩放发生变化,这就是强制重绘的原因,并且有效。您可以通过单击图像下方的复选标记来查看我希望鼠标悬停/移出时发生的情况。
这是页面,所有 HTML 和 Javascript 代码都在那里可见(页面下方)。任何见解都值得赞赏。
到目前为止,我能做的最好的事情是通过在 HTML 中指定 out 来让事件附加到周围的 div 上,就 div 而言,它们在其中做了几乎正确的事情。但是当鼠标悬停在图像上时,它不在 div 中,所以与我想要的相反:onmouseout 触发并且我想要在图像上发生的事情消失了。
是否有某些原因我无法在计时器期间附加这些功能?这是计时器代码:
function mousingover()
{
console.log('over');
if (dismode == 1) return;
show_image_notes('mypic');
}
function mousingaway()
{
console.log('away');
if (dismode == 0) return;
show_image('mypic');
}
function ticker()
{
// var pic = document.getElementById('mypic'); // get (eventually) ready element
// var eltype = pic.nodeName;
// console.log('eltype:',eltype);
// pic.onmouseenter = function() { mousingover(); }
// pic.onmouseout = function() { mousingaway(); }
// console.log(pic.onmouseout);
// When the display is rescaled, the width of this div changes
// This is used to re-fire the calculation of where the notes go:
var myAnchor = document.getElementById('picdiv');
var xd = myAnchor.offsetWidth;
if (working == 0 && xd != xdim)
{
working = 1;
if (dismode == 1) show_image_notes('mypic');
else show_image('mypic');
xdim = xd;
working = 0;
}
tcounter = tcounter + 1;
if (tcounter > 10 || tcounter < 0) // trying to delay so image has time to load
{
var pic = document.getElementById('mypic'); // get (eventually) ready element
pic.onmouseenter = function() { mousingover(); }
pic.onmouseout = function() { mousingaway(); }
tcounter = 0;
}
}
控制台确认我找到了具有该 ID 的 IMG,这是正确的,并且功能已附加。他们只是不开火。
我正在积极解决这个问题,所以计时器的代码会改变;该页面始终显示当前正在使用的代码。
我正在尝试使用纯 Javascript 来做到这一点。
解决方案
我查看了您的 HTML,您canvas
在其中有一个元素以及该img
元素。看起来画布覆盖了图像,是吗?如果是这样,画布将获得鼠标事件,而 img 将看不到它们。
推荐阅读
- android - 以编程方式在 Android 中设置默认拨号应用
- arrays - Laravel,VueJS - 在拖放时保持 2 个数组同步
- date - 雪花中的 VARCHAR 到 DATE
- java - 在 Spring Boot Java 中将 GMT 格式字符串转换为日期时间
- python - 在熊猫 python 中,我如何在 DataFrame 中“黑名单”或“白名单”数字
- windows - 配置 git 以支持使用不同操作系统的程序员
- flutter - 向 Flutter 小部件添加一个空的 const 构造函数
- android - 如何在最新的 Android 上检测当前正在运行的应用程序(或前台应用程序)的统计信息?
- java - JLabel 不显示
- swift - SwiftUI - 如何使用动态密钥访问 API 响应数据?