功能:
鼠标放在指定的HTML元素上时,就会出现对应的提示框,提示框可以设置宽度,高度,背景颜色,字体颜色,字体大小,是否有边框,提示信息,是否有圆角。
效果图:
HTML代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
*{
margin:0;
padding:0;
list-style: none;
}
#box1{
position:relative;
width:200px;
height:150px;
background-color: brown;
}
#box2{
position:relative;
width:300px;
height:200px;
background-color:green;
}
</style>
</head>
<body>
<div id="box1">
</div>
<br/><br/><br/><br/>
<div id="box2">
</div>
</body>
</html>
<script type="text/javascript" src="js/tooltip.js"></script>
<script type="text/javascript">
function $(id){
return document.getElementById(id);
}
window.onload = function () {
//给元素id为box1的元素增加提示信息,提示信息的效果使用默认值
new ToolTip({
"domObj":$("box1")//
});
//给元素id为box2的元素增加提示信息,提示信息的效果,宽度300,提示信息是"这是绿色的div"
new ToolTip({
"domObj":$("box2"),"width":300,"title":"这是绿色的div"
});
}
</script>
js代码:tooltip.js
function ToolTip(obj){
let defaultObj = {
"domObj":document.body,
"width":100,
"height":30,
"bgcolor":"#f1f1f1",
"color":"#600000",
"fontSize":"14px",
"border":"1px solid black",
"title":"暂时无提示信息",
"isRadius":true
};
for(let key in obj){
defaultObj[key] = obj[key];
}
//给属性赋值
for(let key in defaultObj){
this[key] = defaultObj[key];
}
this.initEvent();
}
ToolTip.prototype.createUI=function () {
//给父元素增加定位
this.domObj.style.position="relative";
//1、创建div,显示
this.toolTipDom = document.createElement("div");
this.toolTipDom.id = "tooltipId";
this.toolTipDom.style.cssText="position:absolute";
this.toolTipDom.style.left = (this.domObj.offsetWidth-this.width)/2+ "px";
this.toolTipDom.style.top = (this.domObj.offsetHeight-this.height)/2+"px";
this.toolTipDom.style.width = this.width+"px";
this.toolTipDom.style.height =this.height+ "px";
this.toolTipDom.style.backgroundColor=this.bgcolor;
this.toolTipDom.style.color =this.color;
this.toolTipDom.style.fontSize =this.fontSize;
this.toolTipDom.style.border =this.border;
if(this.isRadius){
this.toolTipDom.style.borderRadius = "5px";
}
this.toolTipDom.innerHTML = this.title;
this.domObj.appendChild(this.toolTipDom);
}
ToolTip.prototype.removeUI=function () {
this.domObj.removeChild(this.toolTipDom);
}
ToolTip.prototype.initEvent=function(){
this.domObj.onmouseover = (event)=>{
let evt = event || window.event;
//如果目的地是toolTipDom元素的话,说明是进入了子元素,不添加提示框
if(evt.toElement==this.toolTipDom){
return;
}
this.createUI();
}
this.domObj.onmouseout = (event)=>{
let evt = event || window.event;
//如果目的地是toolTipDom元素的话,说明是离开父元素进入了子元素,不删除提示框
if(evt.toElement==this.toolTipDom){
return;
}
this.removeUI();
}
}