首页 > 解决方案 > 在 JQuery 中的 hr 元素上使用悬停功能

问题描述

我想使用 hr 元素作为导航栏的下划线,但我无法使用 jquery 来移动 hr 的位置。它似乎固定在网页的顶部,当我想要它在下面时,我可以将鼠标悬停在不同的链接上,hr 元素将滑到该链接。有任何想法吗?

html:

    $('#tt').hover(function(){
        console.log("hi");
      $('hr').css("margin-left: 50%");
    
    })
    nav{
      font-size: 1.85em;
    
    }
    
    nav a{
        text-decoration: none;
        color:#000;
        float:left;
        margin-top: 1vh;
    }
    
    #one{
      margin-left: 2vw;
    }
    
    .floatright{
      float:right;
      padding-right: 3vw;
    }
    .floatright a{
        margin-left: 4vw;
    }
    
    
    hr {
      height: .25rem;
      width: 9.5%;
      margin: 0;
      margin-left: 1.3vw;
      background: tomato;
      border: none;
      transition: .3s ease-in-out;
      top: 6vh;
    }
    
    a:hover ~ hr{
      margin-left: 20px;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
            <nav>
              <a id="one" href="#">name</a>
              <div class="floatright">
                <a id="tt" href="#">Link One</a>
                <a href="#">Link Two</a>
                <a href="#">Link Three</a>
                <a href="#">Link Four</a>
                </div>
                <hr />
    
              </nav>
</div>

代码笔: https ://codepen.io/anon/pen/GwzYje

标签: jqueryhtmlcssnavunderline

解决方案


您可以使用简单的 css 来做到这一点。只需删除您的 hr 标签,相关的 css 并添加此 css

nav a:hover {
   text-decoration:underline;
} 

https://codepen.io/anon/pen/rQPqmw

如果你真的想用 jquery 来做,你可以这样做: 这里的 hover 方法对 mouseenter 和 mouseleaves 事件使用两种方法。

$('nav a').hover(function() {
    $(this).css("text-decoration", "underline");
}, function() {
   $(this).css("text-decoration", "none");
})

https://codepen.io/anon/pen/PxVydw


推荐阅读