Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 更改子悬停上的父元素背景位置_Jquery_Html_Css - Fatal编程技术网

Jquery 更改子悬停上的父元素背景位置

Jquery 更改子悬停上的父元素背景位置,jquery,html,css,Jquery,Html,Css,我正在尝试创建一个导航菜单,当鼠标悬停在childli项上时,它将更改parentdiv背景。实际上,我只想移动父背景 这是我的密码: <div id="headerNav"> <li class="navHome"><a href="index.php">Home</a></li> <li class="navServices"><a href="services.php">Services&l

我正在尝试创建一个导航菜单,当鼠标悬停在child
li
项上时,它将更改parent
div
背景。实际上,我只想移动父背景

这是我的密码:

<div id="headerNav">
    <li class="navHome"><a href="index.php">Home</a></li>
    <li class="navServices"><a href="services.php">Services</a></li>
    <li class="navFaq"><a href="faq.php">FAQ</a></li>
    <li class="navGallery"><a href="gallery.php">Gallery</a></li>
    <li class="navContact"><a href="contact-us.php">Contact</a></li>
</div>

  • 因此,我让
    #headerNav
    显示默认背景。当您将鼠标悬停在服务上时,我希望将背景图像向上移动75像素。当您将鼠标悬停在FAQ上时,我想将背景图像向上移动150px,等等


    有人能帮我吗?

    考虑到
    li
    元素是列表项,所以它的父元素应该是例如
    ul
    标记,而不是
    div
    。如果我们设想有效的HTML标记,您可以使用如下内容来操作父元素的
    背景位置
    。我使用
    index()
    方法不硬编码逻辑

    $("#headerNav > li").hover(function() {
        var pos = "0 -" + ($(this).index() * 75) + "px";
        $(this).parent().css("background-position", pos);
    }, function() {
        $(this).parent().css("background-position", "0 0");
    });
    

    演示:

    您可以使用在li上放置一个自定义属性来确定要移动的像素数,并在鼠标悬停在某个项目上时使用jquery,获取属性值,然后访问它的父项以使用该属性设置它的背景位置,这样它将是可伸缩的菜单,并且非常健壮

    $("#headerNav li").hover(function() {
        $(this).parent().css("background-position", $(this).attr("CustomAttributeName"));
    })
    

    jQuery可以通过
    hover()
    函数轻松实现这一点:

    $("li").hover(function() {
        $(this.parentNode).addClass(this.className);
    }, function() {
        $(this.parentNode).removeClass(this.className);
    });
    

    jsiddle:

    你能给我们展示一下运行中的例子吗?根据浏览器支持的级别,你可以使用CSS转换/动画来移动背景图像。在父类的类名中添加或删除
    li
    的整个类名可能是个坏主意;然而,你明白了。可以使用
    li
    的另一个属性,即它的索引或“data-”属性。虽然这并没有真正解决标题中的问题,但我认为这是针对OP的特定情况的最佳解决方案。@adeneo Cat总是让答案更好:)@VisioN完美答案,这正是我所寻找的,但是由于某种原因我不能让它工作。。。你知道为什么吗?这是我的全部代码:我的站点#headerNav{background image:url(images/assets/menu home.png);background repeat:no repeat;}var pos=“0-”+($(this).index()*75)+“px”$(this.parent().css(“背景位置”,pos);},函数(){$(this.parent().css(“背景位置”,“0”);})
    • 用户1078494似乎没有包括JQuery库。使用
      http://code.jquery.com/jquery-latest.min.js
      而不是
      code.jquery.com/jquery latest.min.js
      。此外,您还忘记将JavaScript代码放入DOM就绪块:
      $(function(){…})