7

css利用attr()函数 - 实现文字移动效果

 2 years ago
source link: https://www.fly63.com/article/detial/11468
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

更新日期: 2022-05-07阅读量: 161标签: 函数分享

扫一扫分享

attr()函数介绍

css表达式 attr() 用来获取选择到的元素的某一html属性值,并用于其样式。它也可以用于伪元素,属性值采用伪元素所依附的元素。attr() 表达式可以用于任何CSS属性。

用法:

attr( attr_name )

参数:该函数接受单个参数attr_name,该参数用于保存HTML元素中的属性名称。它是必填参数。

返回值:此函数返回选定元素的属性值。

一旦你知道了这个技巧,你就会吃惊于很多时候它能给你的工作带来的方便!
提示:在新版的CSS3标准中,attr()功能被扩展,可以用在各种CSS标记中。

attr()生成文本内容

元素可以有自定义的属性值,它的命名格式通常为data-*attr(),用于获取元素的这种自定义属性值,并赋值给其伪元素的content作为其生成的内容利用这个函数,我们可以用伪元素在原先文本的基础上“复制”出另一个文本。

实现文字移动效果

比如将鼠标移上去,文字进行移动效果,如下所示:

f l y 6 3 前 端 开 发 网

实现代码

<p class="arrt" data-text="fly63前端开发网">fly63前端开发网</p>
<p class="arrt" data-text="javascript">javascript</p>

<style>
ul,li{
list-style-type: none;
}
.arrt{
display: flex;
padding: 6px;
color: #47cf73;
font-size: 18px;
text-decoration: none;
overflow: hidden;
}
.arrt:hover span{
transform: translateY(-130%);
cursor: pointer;
}
.arrt span{
position: relative;
transition: 0.3s;
}
.arrt span::before{
position: absolute;
content: attr(data-text);
transform: translateY(130%);
}
</style>
<script>
let floatText = document.querySelectorAll(".arrt");
floatText.forEach(link => {
let letters = link.textContent.split("");
link.textContent = "";
letters.forEach((letter, i) => {
let span = document.createElement("span");
span.textContent = letter;
span.style.transitionDelay = `${i / 20}s`;
span.dataset.text = letter;
link.append(span);
});
});
</script>

链接: https://www.fly63.com/article/detial/11468


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK