简体   繁体   English

使用 javascript 为所有 div 元素添加“onmouseover”功能

[英]Using javascript to add an “onmouseover” funciton to all div elements

<p class="glow" onmouseover="mouseOver(this)" onmouseout="mouseOut(this)">Hello</p>

<p class="glow" onmouseover="mouseOver(this)" onmouseout="mouseOut(this)">Hey</p>

This is my current setup.这是我目前的设置。 I'm trying to get both these lines to change color on hovering using the mouse over and mouse out event.我试图让这两条线在使用鼠标悬停和鼠标移出事件悬停时改变颜色。

Unfortunately, I need to do this for all the lines of class "glow" which means I would have to copy the onmouseover="mouseOver(this)" onmouseout="mouseOut(this)" line for every "glow" element.不幸的是,我需要对“glow”类的所有行执行此操作,这意味着我必须为每个“glow”元素复制onmouseover="mouseOver(this)" onmouseout="mouseOut(this)"行。

Is there an easier way to do this using javascript?有没有更简单的方法来使用 javascript 来做到这一点? (I don't want to directly use the css hover class to change the color) (我不想直接使用css悬停类来改变颜色)

Try using querySelectorAll method.尝试使用querySelectorAll方法。

querySelectorAll will return the list of nodes as an array with specified selector (class selector in below example). querySelectorAll将返回节点列表作为具有指定选择器的数组(下面示例中的类选择器)。 You can loop through those nodes and add your onmouseover and onmouseout event.您可以遍历这些节点并添加您的onmouseoveronmouseout事件。

document.querySelectorAll('.glow').forEach((node) => {
    node.onmouseover = mouseOver;
    node.onmouseout = mouseOut;
})

Absolutely, you can access the DOM from your javascript code instead of the other way around.当然,您可以从您的 javascript 代码访问 DOM,而不是相反。

const glowEls = document.querySelectorAll(".glow")
glowEls.forEach((element) => {
   // call your mouseOver function from here
})

Make sure this code is called AFTER the DOM has initialized otherwise your elements will not be found.确保在 DOM 初始化之后调用此代码,否则将找不到您的元素。

To make sure it loads after the DOM initialized either add "defer" to your script tag or put your script tag at the bottom of your body.为了确保它在 DOM 初始化后加载,要么将“defer”添加到您的脚本标签,要么将您的脚本标签放在您的正文底部。

Small side note, it's usually preferred to access the DOM from javascript instead of called javascript from the DOM.小提示,通常更喜欢从 javascript 访问 DOM,而不是从 DOM 调用 javascript。 This way, your html is much cleaner and stays true to it's single purpose.这样,您的 html 就更干净了,并且忠于它的单一目的。

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

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