0
0
mirror of https://github.com/twbs/bootstrap.git synced 2025-03-15 15:29:22 +01:00
Bootstrap/js/src/dom/manipulator.js

83 lines
1.8 KiB
JavaScript
Raw Normal View History

/**
* --------------------------------------------------------------------------
2020-11-11 19:07:37 +02:00
* Bootstrap (v5.0.0-alpha3): dom/manipulator.js
2020-06-16 21:41:47 +03:00
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* --------------------------------------------------------------------------
*/
function normalizeData(val) {
if (val === 'true') {
return true
}
if (val === 'false') {
return false
}
if (val === Number(val).toString()) {
return Number(val)
}
if (val === '' || val === 'null') {
return null
}
return val
}
function normalizeDataKey(key) {
return key.replace(/[A-Z]/g, chr => `-${chr.toLowerCase()}`)
}
const Manipulator = {
setDataAttribute(element, key, value) {
element.setAttribute(`data-${normalizeDataKey(key)}`, value)
},
removeDataAttribute(element, key) {
element.removeAttribute(`data-${normalizeDataKey(key)}`)
},
getDataAttributes(element) {
if (!element) {
return {}
}
const attributes = {
...element.dataset
}
Object.keys(attributes)
.filter(key => key.startsWith('bs'))
.forEach(key => {
let pureKey = key.replace(/^bs/, '')
pureKey = pureKey.charAt(0).toLowerCase() + pureKey.slice(1, pureKey.length)
attributes[pureKey] = normalizeData(attributes[key])
})
return attributes
},
getDataAttribute(element, key) {
return normalizeData(element.getAttribute(`data-${normalizeDataKey(key)}`))
2017-09-26 09:09:40 +02:00
},
2017-09-25 09:09:01 +02:00
offset(element) {
const rect = element.getBoundingClientRect()
return {
top: rect.top + document.body.scrollTop,
left: rect.left + document.body.scrollLeft
}
},
position(element) {
return {
top: element.offsetTop,
left: element.offsetLeft
}
}
}
export default Manipulator