//txt.js
/**
* @param dom 依附的DOM
* @param value 文字内容
* @param color 字体颜色
* @param opacity 透明度
* @param shadowColor 阴影颜色
* @param shadowSize 阴影大小
* @param size 字体大小
* @param x 水平偏移
* @param y 垂直偏移
* @author fangwk
* @since 2016-7-28 15:53:28
*/
function addTextWithDom(dom,value,color,opacity,shadowColor,shadowSize,size,x,y){
//create new DOM
var newDom = document.createElement("p");
//create new TextNode
var txt = document.createTextNode(value);
var offsetX=dom.offsetLeft+x;
var offsetY=dom.offsetTop+y;
var position = "position:absolute;top:"+offsetY+"px;left:"+offsetX+"px;"
var color = "color:"+color+";";
var fontStyle = "font-size:"+size+"px;"
var alpha = "";
var shadow = "";
// For IE8 and earlier
if(newDom.style.opacity == undefined){
alpha = "filter:alpha(opacity="+parseFloat(opacity)*100+");"
}else{
alpha = "opacity:"+opacity+";";
}
//for IE9 and earlier
if(newDom.style.textShadow == undefined){
shadow="filter:glow(color="+shadowColor+",strength="+shadowSize+");";
}else{
shadow = "text-shadow:"+shadowSize+"px "+shadowSize+"px "+shadowSize+"px "+shadowColor+";"
}
var style = color + fontStyle + position + alpha + shadow;
newDom.appendChild(txt);
newDom.setAttribute("style", style);
dom.appendChild(newDom);
//console.log("left:"+dom.offsetLeft+" top:"+dom.offsetTop);
//console.log("left:"+newDom.offsetLeft+" top:"+newDom.offsetTop);
}
//使用txt.js
<script src="js/txt.js"></script>
<script type="text/javascript">
$(function(){
addTextWithDom(document.getElementById("top"),"测试","white",1,"#A518D4",1,20,10,50);
});
</script>
div和img就省略不写了。。。
效果如下: