當用戶進行鼠標框選選擇了頁面上的內容時,把選擇的內容進行上報。
雖然這需求就一句話的事,但是很顯然,沒那么簡單...
因為鼠標框選說起來簡單,就是選擇的內容,但是這包含很多中情況,比如:只選擇文案、選擇圖片、選擇輸入框、輸入框中的內容選擇、iframe、等。
簡單總結,分為以下幾點:
鼠標框選包含以下幾點:
老生常談的技術點了,這里不能用節(jié)流,因為肯定不能你鼠標選擇的時候,隔一段時間返回一段內容,肯定是選擇之后一起返回。
這里用 debounce 主要也是用在事件監(jiān)聽和事件處理上。
事件監(jiān)聽,因為鼠標選擇,不僅僅是鼠標按下到鼠標抬起,還包括雙擊、右鍵、全選。
需要使用事件監(jiān)聽對事件作處理。
Range 接口表示一個包含節(jié)點與文本節(jié)點的一部分的文檔片段。
Range 是瀏覽器原生的對象。
<body>
<ul>
<li>Vite</li>
<li>Vue</li>
<li>React</li>
<li>VitePress</li>
<li>NaiveUI</li>
</ul>
</body>
<script>
// 創(chuàng)建 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 對象表示用戶選擇的文本范圍或插入符號的當前位置。它代表頁面中的文本選區(qū),可能橫跨多個元素。
window.getSelection()
錨指的是一個選區(qū)的起始點(不同于 HTML 中的錨點鏈接)。當我們使用鼠標框選一個區(qū)域的時候,錨點就是我們鼠標按下瞬間的那個點。在用戶拖動鼠標時,錨點是不會變的。
選區(qū)的焦點是該選區(qū)的終點,當你用鼠標框選一個選區(qū)的時候,焦點是你的鼠標松開瞬間所記錄的那個點。隨著用戶拖動鼠標,焦點的位置會隨著改變。
范圍指的是文檔中連續(xù)的一部分。一個范圍包括整個節(jié)點,也可以包含節(jié)點的一部分,例如文本節(jié)點的一部分。用戶通常下只能選擇一個范圍,但是有的時候用戶也有可能選擇多個范圍。
一個用戶可編輯的元素(例如一個使用 contenteditable 的 HTML 元素,或是在啟用了 designMode 的 Document 的子元素)。
首先要清楚,選擇的起點稱為錨點(anchor),終點稱為焦點(focus)。
function debounce (fn, time = 500) {
let timeout = null; // 創(chuàng)建一個標記用來存放定時器的返回值
return function () {
clearTimeout(timeout) // 每當觸發(fā)時,把前一個 定時器 clear 掉
timeout = setTimeout(() => { // 創(chuàng)建一個新的 定時器,并賦值給 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 是否立即執(zhí)行
* @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()
// 判斷選擇內容里面有沒有節(jié)點
if (rangeClone.childElementCount > 0) {
// 創(chuàng)建 div 標簽
const container = document.createElement('div')
// div 標簽 append 復制節(jié)點
container.appendChild(rangeClone)
// 如果復制的內容長度為 0
if (!selection.toString().trim().length) {
// 判斷是否有選擇特殊節(jié)點
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 監(jiān)聽事件
document.addEventListener('mousedown', () => {
selectionchangeMouseTrack = true
})
// 添加 mouseup 監(jiān)聽事件
document.addEventListener(
'mouseup',
debounce(() => {
selectionChangeFun()
}, 100)
)
// 添加 selectionchange 監(jiān)聽事件
document.addEventListener(
'selectionchange',
debounce(() => {
if (selectionchangeMouseTrack) return
selectionChangeFun()
})
)
// 添加 dblclick 監(jiān)聽事件
document.addEventListener('dblclick', () => {
selectionChangeFun()
})
// 添加 contextmenu 監(jiān)聽事件
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; // 創(chuàng)建一個標記用來存放定時器的返回值
return function () {
clearTimeout(timeout) // 每當觸發(fā)時,把前一個 定時器 clear 掉
timeout = setTimeout(() => { // 創(chuàng)建一個新的 定時器,并賦值給 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()
// 判斷選擇內容里面有沒有節(jié)點
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
})
}
大家介紹如何通過 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; /* 圓角 */
}
首先放出html
<body>
<contain class="test1">
<a name="topAnchor"></a>
<div id="top">我是頂部</div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</contain>
<footer>
<button id="backTop1">第一種方式回到頂部</button>
<button id="backTop2">第二種方式回到頂部</button>
<button id="backTop3">第三種方式回到頂部</button>
</footer>
</body>
然后具體操作步驟如下
const backTop1 = document.getElementById("backTop1")
backTop1.addEventListener("click", function (e) {
let a = document.createElement("a")
a.href = "#topAnchor"
e.target.appendChild(a)
a.onclick = function (e) {
e.stopPropagation()
}
a.click()
e.target.removeChild(a)
})
效果如下圖所示
效果很明顯,在事件觸發(fā)之后,頁面立馬跑到的頂部,在交互性沒啥要求的時候,這種做法確實沒啥問題,不過要求高了之后就不行了,會顯得有些突兀。
此 api 需要傳遞 DOM元素相對于window的 left 和 top 的距離,此例子僅展示簡單demo,只考慮 top 坐標
當然它還有一個 behavior 參數,將其設置為 smooth 后,將會出現滑動效果 步驟如下:
代碼如下:
const backTop2 = document.getElementById("backTop2")
const TOP = document.getElementById("top")
const y = TOP.offsetTop
const backTop3 = document.getElementById("backTop3")
backTop3.addEventListener("click", function (e) {
window.scrollTo({ top: y, left: 0, behavior: 'smooth' })
})
效果如下圖所示
從效果上來看,相較于a標簽,該api支持動畫,使得頁面更絲滑
該 api 相較于上一個,節(jié)點信息更加的明確,操作方法也更加的簡潔,更利于后續(xù)的維護
代碼如下
const backTop2 = document.getElementById("backTop2")
const TOP = document.getElementById("top")
backTop2.addEventListener("click", function (e) {
TOP.scrollIntoView({ behavior: "smooth" })
})
效果如下圖所示
從效果上來看,該api和scrollTo的作用是一致的,但是從代碼結構上來說,scrollIntoView會更加的簡潔
以上三種方法是我目前比較常用的,如有不同之處,還望諸君不吝賜教!
作者:pengpeng
鏈接:https://juejin.cn/post/6906142651121139719
來源:掘金
著作權歸作者所有。商業(yè)轉載請聯系作者獲得授權,非商業(yè)轉載請注明出處。
*請認真填寫需求信息,我們會在24小時內與您取得聯系。