我正在尝试像视频中那样创建这种过渡。悬停时我希望文本从右侧滑入。我尝试创建它,但它没有滑过图标,而是滑到图标后面。
这是我的代码:
<div class-"row">
<div class="col-12 col-lg-3 d-none d-md-block">
<div class="site-header__utility-nav-links">
<a class="site-header__utility-nav-link" href="">
<img class="site-header__utility-nav-icon" src="<?php echo get_stylesheet_directory_uri() . '/images/icons/search.svg' ?>" alt="">
<span>search</span>
</a>
<a class="site-header__utility-nav-link" href="">
<img class="site-header__utility-nav-icon" src="<?php echo get_stylesheet_directory_uri() . '/images/icons/info.svg' ?>" alt="">
<span>info</span>
</a>
<a class="site-header__utility-nav-link" href="">
<img class="site-header__utility-nav-icon" src="<?php echo get_stylesheet_directory_uri() . '/images/icons/user.svg' ?>" alt="">
<span>My Housing</span>
</a>
</div>
</div>
</div>
&__utility-nav-links {
display: flex;
justify-content: end;
}
&__utility-nav-link {
margin-left: 18px;
position: relative;
transform: translateX(0);
transition: transform 0.3s ease;
&:hover {
width: 35px;
transform: translateX(-20px);
& .site-header__utility-nav-icon {
}
& span {
opacity: 1;
transform: translateX(-10px);
}
}
& span {
position: absolute;
left: 100%;
white-space: nowrap;
opacity: 0;
transition: 0.3s ease;
transform: translate(0px);
}
}
&__utility-nav-icon {
width: 20px;
height: 20px;
}
如有任何帮助,我们将不胜感激。
您可以在不影响定位的情况下完成此操作。只需在悬停时将文本跨度的width在零和文本的固有宽度之间过渡即可。
问题是您无法在零和
auto
之间平滑地过渡元素的宽度(或高度)。您必须在两个特定宽度之间转换。这就是脚本派上用场的地方......从脚本中,您可以确定元素的固有宽度(使用其 scrollWidth
属性),然后将此值分配给 CSS 属性(变量),然后在样式规则中引用该属性。
.utility-nav-link:hover span {
width: var(--width);
}
演示片段:
document.querySelectorAll('.utility-nav-link span').forEach(s => {
s.style.setProperty('--width', s.scrollWidth + 'px')
})
body {
margin: 3em;
}
.utility-nav-links {
display: flex;
justify-content: end;
gap: 1em;
}
.utility-nav-link {
display: flex;
align-items: center;
gap: 0.5em;
overflow: hidden;
}
.utility-nav-link span {
--width: 0;
transition: 0.3s ease;
width: 0;
white-space: nowrap;
}
.utility-nav-icon {
width: 20px;
height: 20px;
}
.utility-nav-link:hover span {
width: var(--width);
}
<div class="utility-nav-links">
<a class="utility-nav-link">
<img class="utility-nav-icon" src="https://picsum.photos/40">
<span>search</span>
</a>
<a class="utility-nav-link">
<img class="utility-nav-icon" src="https://picsum.photos/42">
<span>info</span>
</a>
<a class="utility-nav-link">
<img class="utility-nav-icon" src="https://picsum.photos/44">
<span>My Housing</span>
</a>
</div>