本文已参与「新人创作礼」活动,一起开启掘金创作之路。
前言
在一些官网类或电商类项目中经常需要将导航栏或者头部做吸顶,保证下滑页面时也能够快速选择到其他页面上,本次就使用原生 JS 完成头部吸顶操作。顺便记录下使用原生 JS 点击按钮复制文本。
使用原生 JS 完成头部吸顶操作
-
通过 querySelector 获取 product 元素节点,获取 product 对象 到其上级层顶部的间隔 offsetTop
-
使用 onscroll 原生方法 监听滚动条滚动的高度
-
当 滚动的高度 大于对象到其上级层顶部的间隔 则对 product 定位进行固定
-
当 其他情况则清空 product 定位的属性
(function (product , productTop , scrollT) {
product = document.querySelector('.product');
productTop = product.offsetTop;
window.onscroll = function () {
scrollT = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop; //对不同浏览器进行适配
if (scrollT >= productTop){
product.style.position = 'fixed';
product.style.top = 4.3 + 'rem';
product.style.left = 0;
}else{
product.style.position = '';
}
}
}())
JS点击按钮复制文本
在PC端上通过点击按钮复制对应文本的业务场景,不经常有,但是让我碰见了,也了解了下实现方法。
-
通过createElement生成一个input输入框,并将其透明度设为0,使得用户无感知;
-
将需要复制的内容赋值到输入框内,(一定要将输入框添加到页面body中)才能使用select函数选中。
-
通过document.execCommand("copy")执行浏览器复制命令,就能将对应文本进行复制了。
-
目前也有说 execCommand() 被废弃了,可以尝试使用 navigator.clipboard.writeText(value)
function handleCopy(text) {
const input = document.createElement('input')
input.style.cssText = 'opacity: 0;';
input.type = 'text';
input.value = text; // 修改文本框的内容
document.body.appendChild(input)
input.select(); // 选中文本
document.execCommand("copy"); // 执行浏览器复制命令
this.$message({message: '复制成功',type: 'success'})
},
funciton handleCopyNew(text) {
navigator.clipboard.writeText(text).then(() => {
this.$message({message: '复制成功',type: 'success'})
})
}