javascript - 删除 mouseleave 上的数据属性

标签 javascript

我有一些导航链接,当鼠标悬停在这些链接上时,会在 body 标记上创建一个数据属性,这使我能够向不同的链接添加背景颜色,这正是我想要的,但是当我将鼠标悬停在这些链接之外时,我想要的是链接的数据属性已被删除或应用了一个类,因此我可以向导航链接添加默认颜色。

这是我的 html 设置:

<nav>
    <a href="#">One</a>
    <a href="#">Two</a>
    <a href="#">Three</a>
</nav>

<p class="One">This is class One.</p>
<p class="Two">This is class Two.</p>
<p class="Three">This is class Three.</p>
<p class="One">This is also class One.</p>
<p class="Two">This is also class Two.</p>
<p class="Three">This is also class Three.</p>

这是将数据属性设置为正文的 JavaScript:

window.addEventListener("load",function(){

    var links = document.querySelectorAll("nav a");
    for(var i=0; i<links.length; i++){
        links[i].addEventListener("mouseover", function(){
            document.querySelector("h1").innerText = this.innerText;
            document.body.setAttribute("data-nav",this.innerText);
        });
    }
});

最佳答案

您可以将“mouseover ”事件更改为“mouseenter ”并添加“mouseleave ”事件。

“mouseenter”事件可以将属性设置为您需要的属性,而“mouseleave”事件将删除该属性。

主要区别

This website has some good examples and specific differences between mouseover, mouseenter, and mouseleave. Below are take-aways from it.

mouseover: The mousemove event triggers when the mouse moves. But that doesn’t mean that every pixel leads to an event. The browser checks the mouse position from time to time. And if it notices changes then triggers the events.

mouseenter: When the mouseenter triggers, it doesn’t matter where it goes while inside the element.

mouseleave: The mouseleave event only triggers when the cursor leaves it.

如果您要更改悬停链接的样式,我建议使用 CSS(而不是 JavaScript)在悬停链接本身上定义样式。如果您要更改未悬停的链接的样式,您仍然可以使用类而不是数据属性,但两者都可以。对您的具体用例进行更多描述可以帮助我使这个答案更加可靠。

jsfiddle example

window.addEventListener("load",function(){
    var links = document.querySelectorAll("nav a");
    for(var i=0; i<links.length; i++){
        links[i].addEventListener("mouseenter", function(){
            document.querySelector("h1").innerText = this.innerText;
            document.body.setAttribute("data-nav",this.innerText);
        });
        links[i].addEventListener("mouseleave", function(){
            document.body.setAttribute("data-nav", '');
        });
    }
});

关于javascript - 删除 mouseleave 上的数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53659613/

相关文章:

javascript - Google Contacts API 不返回输出

javascript - Vuejs 将隐藏输入的值设置为路由参数

Javascript:如何从数组中清除未定义的值

javascript - 插入数据库时​​mysql连接超时(node.js)

java - XMLHttpRequest.open() 之后不会出现 URL 中的 AJAX 变量

javascript - prop 返回 null

javascript - 使用城市名称在 map 上放置标记,而不是在 JavaScript map 库中使用纬度和经度?

javascript - 将 SVG 分享到 Facebook

javascript - 用于模板引擎语言设计的 Javascript 语法正确的符号

javascript - 了解几个 Cookie "Parameter"