【问题标题】:jquery/js gliding/sliding navigation item effectjquery/js 滑动/滑动导航项效果
【发布时间】:2012-01-16 13:53:33
【问题描述】:

我正在尝试破译类似http://www.htmldrive.net/items/demo/71/Dynamic-navigation-menu-with-scrolling-color-glide-followed-with-jQuery 上看到的效果,但我对 jquery/js 不是很熟悉(除非代码全部为我拼写)

我还没有找到很多其他这种菜单效果的例子(我可能使用了错误的关键字)。

谁能帮我弄清楚这些通常是如何创建的?我想在我的网站上这样做(尽管用粗下划线而不是突出显示)。谢谢!

edit-我意识到我可以只使用其中一个插件,但我真的很想了解发生了什么/自己做

【问题讨论】:

标签: javascript jquery css slider jquery-animate


【解决方案1】:

如果您查看演示 (taken out of the iframe),您会看到演示的 JavaScript here,以及一些 CSS here。看起来很简单。

“背景”是菜单 HTML 中的一个单独元素:

<div class="webwidget_menu_glide_sprite"></div>

精灵和菜单的&lt;ul&gt; 都是绝对定位的。 &lt;ul&gt; 的样式设置在精灵上方,并且精灵会根据菜单中&lt;li&gt; 上的hover 事件进行动画处理。


更新:

要计算和执行动画,您需要三个基本步骤:

  • 在&lt;li&gt;s 上收听hover 事件;
  • 根据触发hover效果的项目查找“glide”元素的宽度和位置;
  • 动画到所述宽度和位置。

在最基本的形式中,它看起来有点像这样:

/* 1. Attach the event handler: */
$('#menu li').on('hover', function() {
    /* 2. Find the position and width: */
    var newPosition = $(this).position();
    var newWidth = $(this).outerWidth(true);
    /* 3. Animate: */
    $('#menu .glide').stop().animate({
        'left': newPosition.left,
        'width': newWidth
    });
});

我在网上放了一个更完整的例子:http://jsbin.com/unuyov。

【讨论】:

  • 是的,我知道,我正在盯着 JS。我特别问动画是如何计算/完成的:)
【解决方案2】:

以下是如何创建类似效果的一般概述:

创建一个菜单,每个菜单项都在一个单独的 div 中。下划线可以是图像,绝对位于第一个菜单项的下方。菜单中的每个项目都有一个鼠标悬停功能。该函数将改变下划线的位置(左或右),一次一个像素。为了让它有一个很酷的幻灯片效果,随着它的移动而加速或减速,我建议使用内置插件。

所以菜单项看起来像这样:

<div id="menuitem2" onmouseover="movesliderto('45');">

脚本会是这样的:

var currentpos= '0'; //initial position

function movesliderto(newposition){
  if (currentpos<newposition){ //moving the slider to the right
   for (var i=currentpos; i<newposition; i++) {
    document.getElementById('underline').style.left += 1;
 } else { //moving the slider to the left
   for (var i=newposition; i<currentpos; i++) {
    document.getElementById('underline').style.left -= 1;
 }
}

当然,您希望 foreach 的每次迭代都花费几毫秒,因此您希望将其放入一个定时函数中。

【讨论】:

    猜你喜欢
    • 2021-11-19
    • 1970-01-01
    • 2023-03-18
    • 2010-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    相关资源
    最近更新 更多