使用CSS在导航栏上滑动(动画)背景图像位置

3
我在论坛上找到了这段代码,想知道如何用导航栏实现相同的效果。因此,我会有7个文本链接,当你将鼠标悬停在其中一个链接上时,图片应该滑动到那个文本位置。每个页面都需要从不同的起始位置开始(突出显示导航栏上的当前页面)。
以下是HTML代码:
<div class="box">
<a href"#">Home</a>
</div>

还有CSS:

.rollover a {
    background: url(img/bg_nav_slide.png) no-repeat 0px 0px;
    width: 920px;
    height: 50px;
    display: block;
}
.rollover a:hover {
    background-position: 0px 40px 0px 0px;
}   
.box {
    background: url(img/bg_nav_slide.png) no-repeat;;
    border: 0;
    width: 920px;
    height: 50px;    
    -webkit-transition: background 0.2s ease-in-out;
    -moz-transition: background 0.2s ease-in-out;
    transition: background 0.2s ease-in-out;
}
.box:hover {
    background-position: 40px 0;
}
.box p {
    text-indent: 2px;
}

我认为这可能是你正在寻找的 http://archive.plugins.jquery.com/project/lavalamp2 - Rick Calder
纯CSS不可能实现吗? - phatphish
2个回答

2

0
正面: 您可以在不更改代码的情况下使用任意数量的菜单项,并将此代码用于项目中的许多类似元素。
负面: 您的项目中有一个固定的项目宽度。
HTML:
<div id="nav_btn_container">
    <div>Item 1</div>
    <div>Item 2</div>
</div>

CSS:
    #nav_btn_container > div {
    cursor: pointer;
    background: none;
    width: 120px;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all 0.15s ease;
    height: 40px;
}

#nav_btn_container {
    color: #fff;
    font-size: 16px;
    background: #111;
    background-image: url("icons/btn.svg");
    background-repeat: no-repeat;
    background-position-x: 0;
    transition: all 0.25s ease;
    border-radius: 8px;
    display: inline-flex;
    margin: 10px 0;
    flex-direction: row;
    flex-wrap: nowrap;
    height: 40px;
}

JS:
    $(NAV_BTN_CONTAINER).on("mouseenter", "div", function(event){
       let i = $(this).index();
       $(NAV_BTN_CONTAINER).css("background-position-x", i*120 + "px");
    });

icons/btn.svg:

    <?xml version="1.0" standalone="no"?>
<svg width="120" height="40" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <rect x="0" y="0" rx="8" ry="8" width="120" height="40" style="fill:#191919;"/>
</svg>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接