项目前提:已修改了title的默认样式,主要js代码
function showTitle(el, title) {
const popover = getPopover();
const popoverStyle = popover.style;
if (title === undefined || title==='') {
popoverStyle.display = 'none';
} else {
const elRect = el.getBoundingClientRect();
const elComputedStyle = window.getComputedStyle(el, null);
const rightOffset = parseInt(elComputedStyle.getPropertyValue('padding-right')) || 0;
const topOffset = parseInt(elComputedStyle.getPropertyValue('padding-top')) || 0;
popoverStyle.visibility = 'hidden';
popoverStyle.display = 'block';
popover.querySelector('.popover-content').innerHTML = title;
popoverStyle.left = elRect.left - popover.offsetWidth / 2 + (el.offsetWidth - rightOffset) / 2 + 'px';
popoverStyle.top = elRect.top - popover.offsetHeight + topOffset -5 + 'px';
popoverStyle.display = 'block';
popoverStyle.visibility = 'visible';
}
}
方法1:利用getComputedStyle和getPropertyValue获取元素的样式属性值
获取到当前元素的字体大小
const elComputedStyle = window.getComputedStyle(el, null);
const fontSize= parseInt(elComputedStyle.getPropertyValue('font-size')) || 0;
当 当前元素的字体大小小于等于18时,是小字体,将title的字体大小设置为18px
if (fontSize<=18){
popoverStyle.fontSize = '18px';
}else{
popoverStyle.fontSize = '24px';
popoverStyle.lineHeight = '26px';
}
getComputedStyle和getPropertyValue获取到的始终是实际的值
方法2:将控制字体大小的字段存储到localStorage
获取到存储在localStorage里的值:
const fontSize = localStorage.getItem('isSmallFont');
if (fontSize=="true"){
popoverStyle.fontSize = '18px';
}else{
popoverStyle.fontSize = '24px';
popoverStyle.lineHeight = '26px';
}
总计
1、在方法1中,若代码中getPropertyValue与getComputedStyle连用获取到的始终是实际的值,getPropertyValue和style配合使用时获取到的只是内联样式的值
2、在方法2中,isSmallFont的数值类型为String,而非Boolean