大家介绍如何通过 JS/CSS 实现网页返回顶部效果。
CSS 按钮样式:
#myBtn {
display: none; /* 默认隐藏 */
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
border: none;
outline: none;
background-color: red; /* 设置背景颜色,你可以设置自己想要的颜色或图片 */
color: white; /* 文本颜色 */
cursor: pointer;
padding: 15px;
border-radius: 10px; /* 圆角 */
}
var topBtn=document.getElementById('top');
// 获取视窗高度
var winHeight=document.documentElement.clientHeight;
window.onscroll=function () {
// 获取页面向上滚动距离,chrome浏览器识别document.body.scrollTop,而火狐识别document.documentElement.scrollTop,这里做了兼容处理
var toTop=document.documentElement.scrollTop || document.body.scrollTop;
// 如果滚动超过一屏,返回顶部按钮出现,反之隐藏
if(toTop>=winHeight){
topBtn.style.display='block';
}else {
topBtn.style.display='none';
}
}
topBtn.onclick=function () {
var timer=setInterval(function () {
var toTop=document.documentElement.scrollTop || document.body.scrollTop;
// 判断是否到达顶部,到达顶部停止滚动,没到达顶部继续滚动
if(toTop==0){
clearInterval(timer);
}else {
// 设置滚动速度
var speed=Math.ceil(toTop/5);
// 页面向上滚动
document.documentElement.scrollTop=document.body.scrollTop=toTop-speed;
}
},50);
}
当用户进行鼠标框选选择了页面上的内容时,把选择的内容进行上报。
虽然这需求就一句话的事,但是很显然,没那么简单...
因为鼠标框选说起来简单,就是选择的内容,但是这包含很多中情况,比如:只选择文案、选择图片、选择输入框、输入框中的内容选择、iframe、等。
简单总结,分为以下几点:
鼠标框选包含以下几点:
老生常谈的技术点了,这里不能用节流,因为肯定不能你鼠标选择的时候,隔一段时间返回一段内容,肯定是选择之后一起返回。
这里用 debounce 主要也是用在事件监听和事件处理上。
事件监听,因为鼠标选择,不仅仅是鼠标按下到鼠标抬起,还包括双击、右键、全选。
需要使用事件监听对事件作处理。
Range 接口表示一个包含节点与文本节点的一部分的文档片段。
Range 是浏览器原生的对象。
<body>
<ul>
<li>Vite</li>
<li>Vue</li>
<li>React</li>
<li>VitePress</li>
<li>NaiveUI</li>
</ul>
</body>
<script>
// 创建 Range 对象
const range=new Range()
const liDoms=document.querySelectorAll("li");
// Range 起始位置在 li 2
range.setStartBefore(liDoms[1]);
// Range 结束位置在 li 3
range.setEndAfter(liDoms[2]);
// 获取 selection 对象
const selection=window.getSelection();
// 添加光标选择的范围
selection.addRange(range);
</script>
可以看到,选择内容为第二行和第三行
只选择 li 中的 itePres
可以看出 range 属性对应的值
const range=document.createRange();
const range=window.getSelection().getRangeAt(0)
if (document.caretRangeFromPoint) {
range=document.caretRangeFromPoint(e.clientX, e.clientY);
}
const range=new Range()
Selection 对象表示用户选择的文本范围或插入符号的当前位置。它代表页面中的文本选区,可能横跨多个元素。
window.getSelection()
锚指的是一个选区的起始点(不同于 HTML 中的锚点链接)。当我们使用鼠标框选一个区域的时候,锚点就是我们鼠标按下瞬间的那个点。在用户拖动鼠标时,锚点是不会变的。
选区的焦点是该选区的终点,当你用鼠标框选一个选区的时候,焦点是你的鼠标松开瞬间所记录的那个点。随着用户拖动鼠标,焦点的位置会随着改变。
范围指的是文档中连续的一部分。一个范围包括整个节点,也可以包含节点的一部分,例如文本节点的一部分。用户通常下只能选择一个范围,但是有的时候用户也有可能选择多个范围。
一个用户可编辑的元素(例如一个使用 contenteditable 的 HTML 元素,或是在启用了 designMode 的 Document 的子元素)。
首先要清楚,选择的起点称为锚点(anchor),终点称为焦点(focus)。
function debounce (fn, time=500) {
let timeout=null; // 创建一个标记用来存放定时器的返回值
return function () {
clearTimeout(timeout) // 每当触发时,把前一个 定时器 clear 掉
timeout=setTimeout(()=> { // 创建一个新的 定时器,并赋值给 timeout
fn.apply(this, arguments)
}, time)
}
}
/**
* debounce 函数类型
*/
type DebouncedFunction<F extends (...args: any[])=> any>=(...args: Parameters<F>)=> void
/**
* debounce 防抖函数
* @param {Function} func 函数
* @param {number} wait 等待时间
* @param {false} immediate 是否立即执行
* @returns {DebouncedFunction}
*/
function debounce<F extends (...args: any[])=> any>(
func: F,
wait=500,
immediate=false
): DebouncedFunction<F> {
let timeout: ReturnType<typeof setTimeout> | null
return function (this: ThisParameterType<F>, ...args: Parameters<F>) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const context=this
const later=function () {
timeout=null
if (!immediate) {
func.apply(context, args)
}
}
const callNow=immediate && !timeout
if (timeout) {
clearTimeout(timeout)
}
timeout=setTimeout(later, wait)
if (callNow) {
func.apply(context, args)
}
}
}
nterface IGetSelectContentProps {
type: 'html' | 'text'
content: string
}
/**
* 获取选择的内容
* @returns {null | IGetSelectContentProps} 返回选择的内容
*/
const getSelectContent=(): null | IGetSelectContentProps=> {
const selection=window.getSelection()
if (selection) {
// 1. 是焦点在 input 输入框
// 2. 没有选中
// 3. 选择的是输入框
if (selection.isCollapsed) {
return selection.toString().trim().length
? {
type: 'text',
content: selection.toString().trim()
}
: null
}
// 获取选择范围
const range=selection.getRangeAt(0)
// 获取选择内容
const rangeClone=range.cloneContents()
// 判断选择内容里面有没有节点
if (rangeClone.childElementCount > 0) {
// 创建 div 标签
const container=document.createElement('div')
// div 标签 append 复制节点
container.appendChild(rangeClone)
// 如果复制的内容长度为 0
if (!selection.toString().trim().length) {
// 判断是否有选择特殊节点
const isSpNode=hasSpNode(container)
return isSpNode
? {
type: 'html',
content: container.innerHTML
}
: null
}
return {
type: 'html',
content: container.innerHTML
}
} else {
return selection.toString().trim().length
? {
type: 'text',
content: selection.toString().trim()
}
: null
}
} else {
return null
}
}
/**
* 判断是否包含特殊元素
* @param {Element} parent 父元素
* @returns {boolean} 是否包含特殊元素
*/
const hasSpNode=(parent: Element): boolean=> {
const nodeNameList=['iframe', 'svg', 'img', 'audio', 'video']
const inpList=['input', 'textarea', 'select']
return Array.from(parent.children).some((node)=> {
if (nodeNameList.includes(node.nodeName.toLocaleLowerCase())) return true
if (
inpList.includes(node.nodeName.toLocaleLowerCase()) &&
(node as HTMLInputElement).value.trim().length
)
return true
if (node.children) {
return hasSpNode(node)
}
return false
})
}
/**
* 获取框选的文案内容
* @returns {string} 返回框选的内容
*/
const getSelectTextContent=(): string=> {
const selection=window.getSelection()
return selection?.toString().trim() || ''
}
// 是否时鼠标点击动作
let selectionchangeMouseTrack: boolean=false
const selectionChangeFun=debounce(()=> {
const selectContent=getSelectContent()
console.log('selectContent', selectContent)
// todo... 处理上报
selectionchangeMouseTrack=false
})
// 添加 mousedown 监听事件
document.addEventListener('mousedown', ()=> {
selectionchangeMouseTrack=true
})
// 添加 mouseup 监听事件
document.addEventListener(
'mouseup',
debounce(()=> {
selectionChangeFun()
}, 100)
)
// 添加 selectionchange 监听事件
document.addEventListener(
'selectionchange',
debounce(()=> {
if (selectionchangeMouseTrack) return
selectionChangeFun()
})
)
// 添加 dblclick 监听事件
document.addEventListener('dblclick', ()=> {
selectionChangeFun()
})
// 添加 contextmenu 监听事件
document.addEventListener(
'contextmenu',
debounce(()=> {
selectionChangeFun()
})
)
也可以进行封装
/**
* addEventlistener function 类型
*/
export interface IEventHandlerProps {
[eventName: string]: EventListenerOrEventListenerObject
}
let selectionchangeMouseTrack: boolean=false
const eventHandlers: IEventHandlerProps={
// 鼠标 down 事件
mousedown: ()=> {
selectionchangeMouseTrack=true
},
// 鼠标 up 事件
mouseup: debounce(()=> selectionChangeFun(), 100),
// 选择事件
selectionchange: debounce(()=> {
if (selectionchangeMouseTrack) return
selectionChangeFun()
}),
// 双击事件
dblclick: ()=> selectionChangeFun(),
// 右键事件
contextmenu: debounce(()=> selectionChangeFun())
}
Object.keys(eventHandlers).forEach((event)=> {
document.addEventListener(event, eventHandlers[event])
})
function debounce (fn, time=500) {
let timeout=null; // 创建一个标记用来存放定时器的返回值
return function () {
clearTimeout(timeout) // 每当触发时,把前一个 定时器 clear 掉
timeout=setTimeout(()=> { // 创建一个新的 定时器,并赋值给 timeout
fn.apply(this, arguments)
}, time)
}
}
let selectionchangeMouseTrack=false
document.addEventListener('mousedown', (e)=> {
selectionchangeMouseTrack=true
console.log('mousedown', e)
})
document.addEventListener('mouseup', debounce((e)=> {
console.log('mouseup', e)
selectionChangeFun()
}, 100))
document.addEventListener('selectionchange', debounce((e)=> {
console.log('selectionchange', e)
if (selectionchangeMouseTrack) return
selectionChangeFun()
}))
document.addEventListener('dblclick', (e)=> {
console.log('dblclick', e)
selectionChangeFun()
})
document.addEventListener('contextmenu',debounce(()=> {
selectionChangeFun()
}))
const selectionChangeFun=debounce(()=> {
const selectContent=getSelectContent()
selectionchangeMouseTrack=false
console.log('selectContent', selectContent)
})
const getSelectContent=()=> {
const selection=window.getSelection();
if (selection) {
// 1. 是焦点在 input 输入框
// 2. 没有选中
// 3. 选择的是输入框
if (selection.isCollapsed) {
return selection.toString().trim().length ? {
type: 'text',
content: selection.toString().trim()
} : null
}
// 获取选择范围
const range=selection.getRangeAt(0);
// 获取选择内容
const rangeClone=range.cloneContents()
// 判断选择内容里面有没有节点
if (rangeClone.childElementCount > 0) {
const container=document.createElement('div');
container.appendChild(rangeClone);
if (!selection.toString().trim().length) {
const hasSpNode=getSpNode(container)
return hasSpNode ? {
type: 'html',
content: container.innerHTML
} : null
}
return {
type: 'html',
content: container.innerHTML
}
} else {
return selection.toString().trim().length ? {
type: 'text',
content: selection.toString().trim()
} : null
}
} else {
return null
}
}
const getSpNode=(parent)=> {
const nodeNameList=['iframe', 'svg', 'img', 'audio', 'video']
const inpList=['input', 'textarea', 'select']
return Array.from(parent.children).some((node)=> {
if (nodeNameList.includes(node.nodeName.toLocaleLowerCase())) return true
if (inpList.includes(node.nodeName.toLocaleLowerCase()) && node.value.trim().length) return true
if (node.children) {
return getSpNode(node)
}
return false
})
}
*请认真填写需求信息,我们会在24小时内与您取得联系。