Javascript 鼠标悬停时如何使用DOM更改可见性css属性

Javascript 鼠标悬停时如何使用DOM更改可见性css属性,javascript,css,dom,Javascript,Css,Dom,我从js创建了一个元素,我希望它只在鼠标悬停时出现 实际上调用了回调函数makesVisible,但没有任何更改 我想将可见性从隐藏更改为可见 您可以选择使用不透明度特性。 初始设置为:imgHover.style.opacity=0; 在makeVisible方法中,将其更改为imgHover.style.opacity=1 这个问题的另一个解决方案是在container div上设置addEventListener方法。假设图像周围可以有一个与图像尺寸完全相同的容器 例如: Here you

我从js创建了一个元素,我希望它只在鼠标悬停时出现 实际上调用了回调函数makesVisible,但没有任何更改

我想将可见性从隐藏更改为可见


您可以选择使用不透明度特性。 初始设置为:imgHover.style.opacity=0; 在makeVisible方法中,将其更改为imgHover.style.opacity=1

这个问题的另一个解决方案是在container div上设置addEventListener方法。假设图像周围可以有一个与图像尺寸完全相同的容器

例如:

Here you were appending element like this 
imgContainer.appendChild(imgHover);
So reference for imgHover element in dom will get 
change. Fetch that element once again inside 
makeVisible() function.
document.querySelector("img") // use your appropriate.

问题是,不透明度和可见性在某种意义上是相同的,不会折叠元素应该占据的空间。尽管隐藏元素将忽略鼠标/指针事件,但有什么不同。

如果您设置了对imgContainer的有效引用,并且为动态创建的元素设置了图像的有效路径,那么代码的工作方式应该是:

var imgContainer=document.getElementByIdcontainer; var imgHover=document.createElement'img'; imgHover.setAttributesrc,https://www.wpclipart.com/signs_symbol/arrows/button_arrows/play_buttons/play_button_gray.png; imgHover.style.width=30px; imgHover.style.height=23px; imgHover.style.position=绝对值; imgHover.style.margin=0自动; imgHover.style.left=45px; imgHover.style.bottom=35px; imgHover.style.visibility=隐藏; imgContainer.appendChildimgHover; imgContainer.addEventListenermouseover,makeVisible,false; 函数makeVisible{ imgHover.style.visibility=可见; }
将鼠标悬停在MeimgHover.style.display='unset'上以显示,将imgHover.style.display='none'以隐藏使用display prop的任何更改
Here you were appending element like this 
imgContainer.appendChild(imgHover);
So reference for imgHover element in dom will get 
change. Fetch that element once again inside 
makeVisible() function.
document.querySelector("img") // use your appropriate.
imgContainer.addEventListener("mouseover", makeVisible, false);