效果图:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
*{
margin:0;
padding:0;
list-style: none;
}
#box{
position:relative;
width:400px;
height:300px;
background-color: brown;
}
#box2{
position:relative;
width:600px;
height:200px;
}
</style>
</head>
<body>
<div id="box">
</div>
<br/><br/><br/><br/>
<div id="box2">
</div>
</body>
</html>
<script type="text/javascript">
function $(id){
return document.getElementById(id);
}
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();
}
}
window.onload = function () {
new ToolTip({"domObj":$("box")});
}
</script>