从左jquery滑动动画栏位置

时间:2019-02-19 20:11:42

标签: javascript jquery html css

我在导航时将鼠标悬停在一个滑动动画上,其工作正常,但是当我将鼠标悬停在任何菜单项上时,滑动条从最左边开始,而应该从导航项开始的地方开始

这里是JSfiddle

$(".mega-navigation--level-one").append("<span class='nav-hover'></span>");
	var $magicLine = $(".nav-hover");
    $magicLine
        .width($(".active > a").innerWidth())
        .css("left", $(".nav-hover").position().left - 400)
        .data("origLeft", $magicLine.position().left)
        .data("origWidth", $magicLine.width());

    $(".mega-navigation--level-one > li").hover(function () {
        $el = $(this);
        leftPos = $el.position().left + 20;
        newWidth = $el.width();

        $magicLine.stop().animate({
            left: leftPos,
            width: newWidth,
            opacity: 1
        });
        console.log($magicLine.data("origLeft"));
    }, function () {
        $magicLine.stop().animate({
            left: $magicLine.data("origLeft"),
            width: $magicLine.data("origWidth")
        });
    });
.mega-navigation--level-one {
    position: relative;
    list-style: none;
    padding: 0;
    margin: 0 auto;
    width:400px;
}
.mega-navigation--level-one > li {
  display:inline-block;
  margin: 0 10px;
}
.mega-navigation--level-one > li > a {
  color:#000; 
  font-weight:bold; 
  text-decoration:none;
}
.nav-hover {
  position: absolute;
  bottom: -12px;
  left: 0;
  width: 100px;
  height: 6px;
  background: #04aa84;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="mega-navigation--level-one">
	<li>
		<a href="#">Menu Item 1</a>
	</li>
	<li>
		<a href="#">Menu Item 2</a>
	</li>
	<li>
		<a href="#">Menu Item 3</a>
	</li>
</ul>

1 个答案:

答案 0 :(得分:0)

请在左侧属性中仅添加10px而不是20px

leftPos = $el.position().left + 10;

您的功能:

$(".mega-navigation--level-one > li").hover(function () {
    $el = $(this);
    leftPos = $el.position().left + 10;
    newWidth = $el.width();

    $magicLine.stop().animate({
        left: leftPos,
        width: newWidth,
        opacity: 1
    });
    console.log($magicLine.data("origLeft"));
}