跳到主要内容

DOM & BOM

代码参考​

选择元素​

一个元素​

通用写法:

documenut.querySelector(选择器)

某个元素下的元素:

elem.querySelector(选择器)

通过 ID:

document.getElementById(ID)

多个元素​

通用写法:

documenut.querySelectorAll(选择器)

其他:

elem.getElementsByClassName('hello')
elem.getElementsByTagName('hello')

元素的位置信息​

元素的样式信息​

滚动​

滚动到指定元素​

判断是否有滚动条​

事件​

KeyboardEvent.isComposing​

KeyboardEvent.isComposing 只读属性,返回一个 Boolean 值,表示该事件是否在 compositionstart 之后和 compositionend 之前被触发。

场景:当避免在输入法回车时触发回车的处理事件。实现:

const handleKeyDown = (e) => {
if(e.key === 'Enter' && !e.isComposing) {
// do something
}
}

在 React 中,isComposing 在 e.nativeEvent 上。

判断该元素是否被hover​

function App() {
const [isHovering, setIsHovering] = useState(false)
return (
<div
onMouseEnter={() => setIsHovering(true)}
onMouseLeave={() => setIsHovering(false)}
>
{isHovering ? 'hovering' : 'leave'}
</div>
)
}

用 ahooks

import { useHover } from 'ahooks'
function App() {
const ref = useRef(null)
const isHovering = useHover(ref)
return (
<div ref={ref}>
{isHovering ? 'hovering' : 'leave'}
</div>
)
}

URL​

URL 信息​

  • locaion.href
  • location.path
  • location.search
  • location.hash

解析 URL 的搜索条件​

API: URLSearchParams。

获取一个搜索条件:

const search = 'name=joel&age=18'// location.search
const searchParams = new URLSearchParams(search)
searchParams.get('name') // 'joel'
searchParams.get('age') // '18'
searchParams.get('other') // null

获取所有的搜索条件:

const searchParams = new URLSearchParams("key1=value1&key2=value2")
for (const key of searchParams.keys()) {
console.log(key);
}

改搜索条件:

const search = 'name=joel&age=18'
const searchParams = new URLSearchParams(search)
searchParams.set('name', 'jack')
searchParams.toString() // name=jack&age=18

复杂的生成或解析 URL 参数​

使用库:qs。

比如:ids = [1, 2, 3] 要生成的参数是 ids=1&ids=2&ids=3。实现:

qs.stringify(ids, { indices: false })

在 axios 的写法:

{
params: ids,
paramsSerializer: params => {
return qs.stringify(params, { indices: false })
}
}